I'm trying out Alpine.js, but some of the examples doesn't work for me. For example
<button x-on:click="alert('Hello World!')">Say Hi</button>
This doesn't alert anything.
<button x-on:click="console.log('test')">Log</button>
And this doesn't log anything into the console. However other things work:
<div x-data="{ count: 0 }">
<button x-on:click="count--">Decrement</button>
<code>count: </code><code x-text="count"></code>
<button x-on:click="count++">Increment</button>
</div>
This is my whole page:
<!DOCTYPE html>
<html>
<body>
<h1>Works</h1>
<div x-data="{ count: 0 }">
<button x-on:click="count--">Decrement</button>
<code>count: </code><code x-text="count"></code>
<button x-on:click="count++">Increment</button>
</div>
<div x-data="{ open: false }">
<button @click="open = ! open">Expand</button>
<div x-show="open">
Content...
</div>
</div>
<div x-data="{ title: 'Start Here' }">
<h1 x-text="title"></h1>
</div>
<button x-data="{ label: 'Click Here' }" x-text="label"></button>
<h1>Doesn't work</h1>
<button x-on:click="console.log('test')">Log</button>
<button x-on:click="alert('Hello World!')">Say Hi</button>
<button @click="$event.target.remove()">Remove Me</button>
<div @foo="console.log('foo was dispatched')">
<button @click="$dispatch('foo')">Dispatch</button>
</div>
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
</body>
</html>
What am I doing wrong?
Your examples that aren't working don't have an x-data attribute (either on themselves or a parent). Whether there's data or not, the x-data
attribute is required to get AlpineJS functionality.
If you wrap the entire "Doesn't work" section in a <div x-data></div>
they should work:
<div x-data>
<button x-on:click="console.log('test')">Log</button>
<button x-on:click="alert('Hello World!')">Say Hi</button>
<button @click="$event.target.remove()">Remove Me</button>
<div @foo="console.log('foo was dispatched')">
<button @click="$dispatch('foo')">Dispatch</button>
</div>
</div>