I have a DOM element with an attribute that is added/removed by an external library (e.g. bootstrap).
Before:
<div x-data="{ fooEnabled: false }">
...
</div>
After:
<div x-data="{ fooEnabled: false }" data-foo="123">
...
</div>
I'd like to toggle fooEnabled
when attribute data-foo
is added/removed.
This can be done with a mutation observer, but I'm hoping it's possible (and easier) using alpinejs. How do I do this?
To be clear if the attribute is added by a non alpinejs method, its not possible to constantly check if element has an specific attribute without using a mutationObserver.
But if its no problem that alpinejs also adds the attribute there is an possibility. I wont go into detail since you probably wont need this piece of code.
<div x-data="{ hasAttribute: false }" x-init="() => hasAttribute = $el.hasAttribute('data-example')">
<button @click="hasAttribute = !hasAttribute">
Toggle Attribute
</button>
<div x-effect="if (hasAttribute) { $el.setAttribute('data-example', 'true'); } else { $el.removeAttribute('data-example'); }">
<p x-text="hasAttribute ? 'Attribute is present' : 'Attribute is absent'"></p>
</div>
</div>
In this way you can add the attribute using alpinejs and the value is also updated.
But this is not the functionality that you asked for.
So for my conclusion NO you can not use alpinejs to check if attribute is present. This concludes that you do need a mutationObserver to check if attribute is added or not.