1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I was hoping alpinejs could handle a mutation observer on my behalf, but I guess not. Thanks for confirming.
By the way, I don't think the x-effect is necessary, the example works without it.
@lonix the x-effect is an event listener on the values it holds that is hasAttribute and when that value changes it executes the code within which is an attribute setter/remover

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.