'Alpine.js :class not working in second element
I'm starting to look into Alpine.js and trying to understand how it works. I have some html with one button to flip the background-color in two other buttons, but the toggle isn't working correctly.
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 class="red" :class="{ 'blue': colored }">
Button 1
</button>
<button class="blue" :class="{ 'red': colored }">
Button 2
</button>
<br><br>
<button @click="colored = ! colored">
Flip Color
</button>
<p x-text="'colored: '+ colored"></p>
</div>
Solution 1:[1]
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 :class="flip ? 'blue' : 'red'">
Button 1
</button>
<button :class="flip ? 'red' : 'blue'">
Button 2
</button>
<br><br>
<button @click="flip = !flip">
Flip Color
</button>
<p x-text="'flipped: '+ flip"></p>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Dauros |