I'm starting to look into Alpine.js and trying to understand how it works. I have a basic pen here with the exact issue I am facing. Basically one button to flip the background-color in two other buttons.
The problem: Button 2 does not take the CSS class after toggling. It always retains its initial class. The weird thing is it only happens when the background-color is blue. If I just have the two buttons be the same as Button 1 (starting red and flipping to blue) they both work fine! What basic thing am I missing here?
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.9.6/cdn.js"></script>
<div x-data="{ colored: false}">
<button :>
Button 1
</button>
<button :>
Button 2
</button>
<br><br>
<button @click="colored = ! colored">
Flip Color
</button>
<p x-text="'colored: ' colored"></p>
</div>
CodePudding user response:
Alpine.js won't remove the original classes from the static class
attribute, so you have a CSS issue in this example (the .red
and .blue
classes overwrite each other). If you want to toggle classes, you have to do that using Alpine.js class binding:
.red {
background-color: red;
}
.blue {
background-color: blue;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/alpinejs/3.9.6/cdn.js"></script>
<div x-data="{flip: false}">
<button :>
Button 1
</button>
<button :>
Button 2
</button>
<br><br>
<button @click="flip = !flip">
Flip Color
</button>
<p x-text="'flipped: ' flip"></p>
</div>