Home

9 minute read

AlpineJS for Beginners

Tony Lea

AlpineJS for Beginners

AlpineJS is a new javascript library/framework that focuses on simple javascript interactivity, and it does it really well. If you're looking for a JS framework with routing, state management, and a bit more complexity. Well then, Vue or React may be a better fit.

Instead, if you're looking to sprinkle a little javascript, add two-way data binding, and create simple components. Then, AlpineJS is the library you will want to reach for.

Alpine puts simplicity back into javascript. In this tutorial, I'm going to teach you the basics of using AlpineJS, so you can see how simple (and powerful) it is.

Install Alpine

Alpine can easily be installed on any website by including the CDN link on your page, like so:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Alpine JS</title>
</head>
<body>

    <script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js" defer></script>
</body>
</html>

It's as simple as that. You can now use Alpine on your page.

You may also wish to include Alpine via NPM, which you can learn how to do from the Alpine Github repo.

Creating a component

Creating your first Alpine component is very simple. All you need to do is add the x-data attribute to any element like so:

<div x-data="{}"></div>

The example will create a new Alpine component with an empty object {} as its data. Of course, this component is pretty useless without any data, so let's create a new one with some data.

<div x-data="{ title: 'Hello Alpine' }">
    <p x-text="title"></p>
</div>

As you can see from the code above, we have a data variable called title, and we are rendering that text out in a paragraph element using the x-text attribute. The x-text attribute (also referred to as a directive) will render the variable passed to it.

Here is a quick codepen example of our first AlpineJS component:

Now, our component doesn't do anything special at the moment. But, since we are utilizing Alpine, we can add some simple interactivity to our component. Let's first cover click events.

Click Events

We can use a new directive called x-on:click and execute some javascript when that element is clicked. Take a look at the code example below. We are changing our title variable when the user clicks the button.

<div x-data="{ title: 'Hello Alpine' }">
    <p x-text="title"></p>
    <button x-on:click="title='Alpine Rocks!'">click me</button>
</div>

You can also use a shorthand syntax for any x-on: event with the @ symbol. So our click directive can be changed to @click, like so:

<div x-data="{ title: 'Hello Alpine' }">
    <p x-text="title"></p>
    <button @click="title='Alpine Rocks!'">click me</button>
</div>

Take a look at the codepen below to view a live example of our new component:

Next, let's see how we can use everything we've learned so far about Alpine to create a simple counter component.

Create a Counter Component

We can easily create a counter component by declaring a count variable, like so:

<div x-data="{ count: 1 }">
    <p x-text="count"></p>
</div>

You can see that we set the initial value to 0 for our counter. if we wanted to add a button to increment our counter, we can do so with the following code:

<div x-data="{ count: 1 }">
    <p x-text="count"></p>
    <button @click="count++">Count Up</button>
</div>

You may also want to add a button that will decrease the counter. Simple enough we can add another button that does the opposite of the other button:

<div x-data="{ count: 1 }">
    <p x-text="count"></p>
    <button @click="count++">Count Up</button>
    <button @click="count--">Count Down</button>
</div>

Take a look at a live example of this component from the codepen below:

You can see that it's just that easy to create a counter in AlpineJS.

Now, we've used a few directives, such as the x-text and the x-on. There are currently 14 directives that we can use in our component to add functionality. Let's quickly cover those other directives.

AlpineJS Directives

Directives are attributes you can add to your elements to attach a specified behavior to that element. Below are the 14 directives you can use in your Alpine components to attach some behavior.

  1. x-data - creates a new alpine component and allows you to add data to your component.
  2. x-init - executes javascript code when the component is initialized—more info on this directive in the next section.
  3. x-show - show or hide an element based on a true or false variable.
  4. x-bind - set the value of an attribute based on a condition. example x-bind:disabled="isDisabled".
  5. x-on - execute javascript based on a JS event listener. example: x-on:click="console.log('i got clicked')".
  6. x-model - two-way data bind variable to element. Will keep both element and variable data in sync.
  7. x-text - sets the innerText of an element equal to the variable data.
  8. x-html - sets the innerHTML of an element equal to the specified variable data.
  9. x-ref - This allows you to add a reference to this element to refer to it elsewhere.
  10. x-if - If the condition is not met inside this directive, the element will be removed from the DOM and must be used inside a <template> tag.
  11. x-for - Loops through an array of items and creates new nodes for each item in the array. Must also be used in a <template> tag.
  12. x-transition - Directive for applying classes to the different stages of an element's transitions.
  13. x-spread - This allows you to bind an object of an Alpine directive with an element for better re-usability.
  14. x-cloak - Attribute used on an element to hide it from the DOM until the component is ready. Learn more about x-cloak from this article.

Those are the directives you can use inside of your AlpineJS components. Get to know most of them, and you will be an AlpineJS ninja 🥋.

Below, we are only going to cover the most useful directives. We have already covered the x-data and the x-on directive.

Next, let's learn about the x-init, x-show, x-model, x-html, x-ref, x-if, and x-for directives. Let's kick it off with the x-init directive.

AlpineJS x-init

The x-init directive will allow you to run some javascript code when a component is ready and initialized.

Here is a quick example of a small timer countdown component where we add a simple setInterval inside the x-init directive to count down our timer.

<div x-data="{ countdown: 60 }"
     x-init="setInterval(function(){
                countdown--;
             }, 1000);
             ">
    <h1 x-text="countdown"></h1>
</div>

You can check out an example of our timer countdown in the codepen below:

Anytime you need some code to be executed as soon as your component is ready, you can add that code to your x-init directive.

AlpineJS x-show directive

Next, if we want to show or hide an element optionally, we can use the x-show directive.

As an example say that we have a simple button that will toggle the visibility of another element. That can easily be accomplished with the following code:

<div x-data="{ show: false }">
    <button @click="show=!show">Show</button>
    <div x-show="show">Hello</div>
</div>

You can take a look at this simple example from the codepen below. Click the show button to toggle the display.

Pretty straight forward, right? In addition to the x-show directive, we can also add a simple transition to the element visibility.

Take a look at the same example. This time we'll add a transition to the directive x-show.transition="show", and we'll get a nice little transition when the element is toggled.

There are also some more advanced transitions you can use to customize the in-and-out transition effects. You can take a look at the official AlpineJS read me to learn more about the x-transition directives.

Next, let's add some two-way data-binding with the x-model directive.

AlpineJS x-model

The x-model directive will allow you to bind a variable to a form element such as a textbox. Here is a simple example of this:

<div x-data="{ title: 'AlpineJS is Awesome' }">
    <p x-text="title"></p>
    <input type="text" x-model="title">
</div>

As you can see, our textbox is bound to the variable title. Whenever you update the value of the variable or the text box's value, they will stay in sync. Take a look at the codepen example below.

Alpine really makes it easy to add some two-way data binding awesomeness.

Next, let's learn how we can add some dynamic HTML using the x-html directive.

AlpineJS x-html

Using the x-html directive, we can add some dynamic HTML inside any element.

Here is a quick example:

<div x-data="{ code: '<p>Dynamic Paragraph</p>' }">
    <div x-html="code"></div>
</div>

You can see from the Codepen below that we inject a dynamic paragraph inside of the div element.

In addition to using the x-html directive, which will set the innerHTML of any element, we can also use the x-text directive to set the innerText of any element.

Next, we'll learn how we can easily use the x-ref directive to reference any element inside an Alpine component.

AlpineJS x-ref

The x-ref directive will allow us to reference any element with a specified name. Take the following component as an example:

<div x-data="{ code: '<p>Dynamic Paragraph</p>' }">
    <div x-ref="sentence">I am a sentence</div>
    <button @click="$refs.sentence.innerText = 'I just changed'">Change Sentence</button>
</div>

As you can see, when we click the button, we reference $refs.sentence, which will return the element with the x-ref="sentence".

Here is a quick codepen example of this component:

AlpineJS x-if

We can show or hide elements based on a conditional by using the x-if directive. Take a look at the following example:

<div x-data="{ socks: 'blue' }">
    <template x-if="socks=='blue'">
        <p>My socks are blue</p>
    </template>
    <template x-if="socks=='green'">
        <p>My socks are green</p>
    </template>
    <button @click="socks = 'green'">Change Sox</button>
</div>

Using this directive will show or hide the specified element from the DOM. In the example above, we will display a paragraph if socks == 'blue' or show another paragraph if they are equal to green.

Here is a codepen example of this component below.

Note: remember that the x-if directive must be used inside <template> tags.

AlpineJS x-for

If we want to loop through an array of items inside of our Alpine component we can use the x-for directive. Take a look at the following code example, where we loop over a list of groceries:

<div x-data="{ groceries: ['Milk', 'Eggs', 'Cheese'] }">
    <p>Groceries</p>
    <ul>
        <template x-for="item in groceries">
            <li x-text="item"></li>
        </template>
    </ul>
</div>

As you can see from the codepen below, we are looping through the array of groceries and displaying each item in a list.

Conclusion

AlpineJS is a javascript framework/library that allows you to add interactive elements on your page easily. Be sure to check out the official Repo and Readme to learn all the ins-and-outs of this awesome library.

Pairing Alpine with Laravel Livewire is like putting Peanut Butter on your Jelly Sandwich. It makes creating applications so much better and easier. If you are not familiar with Livewire, click here to check out my introduction to Livewire video.

Happy Coding ✌️

🎁 One last thing. If you are interested in creating some beautiful pages with Alpine and TailwindCSS, be sure to check out Tails, the ultimate Alpine and Tailwind Drag'n Drop page builder 🛠