How to handle nested attributes in HTMX

Viewed 201

I have a table like structure in my page and each row has data-hx-get attribute pointing to a url where django returns details for that row. But also in the same row I have an edit button where django returns the edit form for that item. I would like the entire row to be clickable and when clicked shows replaces itself with the details and also the edit button to replace the row with the form. It works fine for the users but when the edit button inside the row is clicked, in the console I get htmx:swapError as the row also receives the click event and does what it was supposed to do. The event on the button takes precedence and before the row it changes the content of the row and when the row gets the response, the data-hx-target for that is no more in the page. So, my question is, is there a way to tell htmx, when a nested element has data-hx-get, ignore the parent's hx directive.

<div 
    class="row item-row" 
    id="item-row-{{item.pk|unlocalize}}"
    data-hx-get="{% url 'some url' item.pk %}
    data-hx-swap="outerHTML"
    data-hx-trigger="click"
    data-hx-target="this">
            ...
         <button
            data-hx-get="{% url 'editurl' item.pk %}"
            data-hx-swap="outerHTML"
            data-hx-trigger="click"></button>
</div>
1 Answers

You can use the consume modifier for hx-trigger https://htmx.org/attributes/hx-trigger/. This will prevent the click event from bubbling up to the parent row.

<div 
    class="row item-row" 
    id="item-row-{{item.pk|unlocalize}}"
    data-hx-get="{% url 'some url' item.pk %}"
    data-hx-swap="outerHTML"
    data-hx-trigger="click"
    data-hx-target="this">
            ...
         <button
            data-hx-get="{% url 'editurl' item.pk %}"
            data-hx-swap="outerHTML"
            data-hx-trigger="click consume"></button>
</div>
Related