How do you activate alpinejs?

Viewed 619

I'm trying to add AlpineJS to a very simple html page that I'm working on and the package is being executed (from cdn) but it doesn't seem to get activated correctly. Even on this small snippet of HTML, it doesn't work:

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
    </head>
    <body>
        <h1 x-show="false">hide me</h1> <!-- doesn't work-->
    </body>
    <script type="text/javascript">
        console.log($el); //undefined
    </script>
</html>

This is also loaded into a codepen where the problem can be observed: https://codepen.io/dwarburt/pen/gOgZyeR

I'm sure I've just missed a step, but what could it be? AlpineJS is executing its initialization routines, you can tell from the debugger.

2 Answers

To initialise an AlpineJs component you'll need an x-data attribute on the parent container:

<div x-data="{
    isShowing: false
}">
    <h1 x-show="isShowing">I am hidden</h1>
</div>

This contains an object with properties and functions you can use within the component instance.

It's definitely worth reading through the docs in the repo here: https://github.com/alpinejs/alpine#use

I have adjusted your example in order to achieve the result you require, along with an additional example so you can see how multiple object properties can exist and used within your Alpine.js components.

x-data does not need to be initiated on the body tag, however nested components will retrieve the object property from the closest x-data property match.

You can access from child nodes of nested x-data objects the properties.

Careful of your property naming conventions if you don't wish to overwrite proceeding object properties.

I would also suggest reading Build a Drop Down along with Toggle Element

Reading these points will be helpful in understanding the below example in further detail.

<html>

<head>
  <script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
</head>

<body x-data="{show: false, button: 'Toggle'}">
  <button @click="show = ! show" x-text="button"></button>

  <span x-show="show">
  <h1 @click.outside="show = false">hide me</h1> <!-- doesn't work-->
</span>

</body>

</html>

Related