How do I swap/remove an element out of band, but ignore any target errors if it doesn't exist? #3454
Replies: 2 comments 2 replies
-
|
I think you can solve this easier with just a bit of CSS. <table>
<tbody id="todo-body">
<!-- TODO <tr>s here -->
</tbody>
</table>
<div id="empty-placeholder">Nothing to do!</div>#empty-placeholder {
display: none;
}
#todo-body:has(tr) + #empty-placeholder {
display: none;
}
/* If tbody does NOT have a tr, show the message */
#todo-body:not(:has(tr)) + #empty-placeholder {
display: block;
} |
Beta Was this translation helpful? Give feedback.
-
|
Another great way to perform custom actions like removing or showing toasts and notifications like this is to do it with the hx-trigger response header. you just add a couple of lines of JS in an event listener on the page that listens to a custom event name and performs the required custom action you want. You can then just add logic in the backend to optionally add hx-trigger response header with the event when the backend detects the empty table or whatever. You can also include message text in the hx-trigger response to be processed in the event listener if you want. This moves all the control to the backend while the client is kept simple. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
My scenario is as follows:
I have a table that shows a bunch of TODOs. Users can add new ones, delete them, and edit them. This all works fine.
When the last TODO is removed from the table, I want to show some sort of "Nothing to do!" message. I currently do this by having the "delete a TODO" request handler change its response when the last TODO is removed. This means that if you have just one TODO remaining and delete it:
You end up with this:
Now when one adds a new TODO again, I would like to remove that placeholder. This is where things get a bit tricky. I had hoped that I could just have an OOB swap in the "TODO created" response that removes the placeholder. While this works, it only does so if the placeholder is actually present, producing this (as expected):
However, the next time you try to create a new TODO (and thus try to swap the placeholder out again), you'll run into a oobErrorNoTarget error because the target element no longer exists (because creating the first new TODO removed it).
What is the best way to swap/remove an element, but only if it in fact exists? On paper something like this would be nice:
Right now my "hack" is to use a
hx-on::after-requestattribute that containshtmx.find("tr.empty")?.remove()(wheretr.emptyis the selector for the placeholder). While this works, it feels a bit janky and gets especially annoying when you want to combine it with other JS (e.g. to reset a form).Beta Was this translation helpful? Give feedback.
All reactions