Alpine.js x-bind not applying after an HTMX swap #3985
-
Hi. I'm not sure this officially counts as a bug but I ran into the same issue as this post : https://stackoverflow.com/questions/76891618/alpine-js-x-bind-not-applying-after-an-htmx-swap The issue is that when swapping an element with htmx the x-binding was not working after the swap. (The state was not being swapped so that was not the issue.) Someone in the comments suggested removing the id from the element and that worked! I have no idea why that worked and it doesn't sound like the one who wrote that in the StackOverflow post understood why either. Here is the code I am using (this is without the id): <div
x-data="{value:{{item.pk}}}"
class=" mock-checkbox"
:class=" {'checked':$store.checked.values.includes($data.value) }"
@click="$el.classList.contains('checked') ? $store.checked.remove($data.value) : $store.checked.add($data.value)">
<span class='mock-checkbox-check'>✓</span>
</div> |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 15 replies
-
🤔 That's curious. the id shouldn't really matter unless htmx is doing something strange with them... |
Beta Was this translation helpful? Give feedback.
-
Are you using https://htmx.org/extensions/alpine-morph/? |
Beta Was this translation helpful? Give feedback.
-
Oooh, yes, are you using alpine morph plugin? I can't imagine this issue would happen without using that since it should just be seen as totally different elements... |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
-
Oh, your conditions are just strange and causing issues. You should just be using |
Beta Was this translation helpful? Give feedback.
-
Hello I ran into the same issue and could reproduce it in a Codepen: https://codepen.io/shimikano/pen/MWREmPO The component in question is: <div x-data="{ valid: true }">
<label for="foo" x-text="'The border should be ' + (valid ? 'green' : 'red') + ': '"></label>
<input id="foo" name="foo" value="bar" :class="valid ? 'valid' : 'invalid'">
</div> When htmx swaps in the same markup with Does anyone have some insight as to how and where (alpine or htmx) this can be tackled? Using plain htmx and alpinejs, without any plugins. Thank you. |
Beta Was this translation helpful? Give feedback.
Thank you for your reply @SimoTod.
After some more digging, I understand now that the culprit is the default htmx swap/settle algorithm for elements with an
id
(documented here). There is also a corresponding htmx issue.Possible workarounds include:
id
attribute.settle:0
).htmx.config.attributesToSettle
.I updated the Codepen, demonstrating 2 workarounds.