Skip to main content

Alpine.js Tutorial 01 - The Basics

·1096 words·6 mins·
Alpine.js Tutorial - This article is part of a series.
Part 1: This Article

What is Alpine.js?
#

Alpine.js is a lightweight JavaScript framework that allows you to add interactivity to your web pages with minimal effort. It works directly within HTML files by adding simple declarative attributes to elements. It is created by the man himself Caleb Porzio and is often described as “jQuery for the modern web” or “Vue.js for the HTML-first developer.” What makes it different from the hundreds of other JavaScript libraries and frameworks out there? We can just drop the CDN link into any HTML page without any kind of build setup. It’s much easier and simpler to get started with. Alpine.js is probably the best choice for small to medium-sized projects when you don’t need all the overhead of larger frameworks like React or Vue.js.

That’s a broad view of what Alpine.js is. We’ll dive deeper as we progress through this tutorial series. During this tutorial, we will be using Alpine to make an interactive form. We’ll add some features like character counters, password visibility toggles, form validation, and more.

Setting Up Alpine.js
#

Let’s go to alpinejs.dev and see how we can get started. If we go to the “Installation” section in the docs, we can see that there are two ways to include Alpine.js in our project: via CDN or by installing it using npm. We are gonna use the CDN method. To include Alpine.js in your HTML file, simply add the script tag mentioned in the documentation within the <head> section of your HTML file. Make sure to replace 3.x.x with the version you want to use, when you use this in production.

First Steps
#

First create a new HTML file and add the following code:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Alpine.js Tutorial</title>
  <link rel="stylesheet" href="styles.css">

  <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>
<body>


</body>
</html>

As you can see, we have included the Alpine.js script in the <head> section. I also added a link to a CSS file, that’s because later in the tutorial when we make a web form it’s going to look a bit better. The CSS file can be accessible here. It’s just some basic styling for the form, nothing fancy.

Creating Our First Alpine Component
#

Let’s start with the most basic example we can use, a counter. Just to explore the syntax and methodology behind Alpine. Add the following code inside the <body> tag:

<div x-data="{ count: 0 }">
    <p>The current value of the count is: <span x-text="count"></span></p>
</div>

Here, we have created a div element with the x-data attribute. This attribute initializes an Alpine.js component and defines its reactive data. In this case, we have a single property called count, which is initialized to 0. This property could be an object, a boolean, a number, a string, or even a function. The div covered by x-data is now an Alpine component, and we can use its data and methods within this scope. Inside the span element, we have used the x-text directive to bind the text content of the span to the count property. This means that whenever the value of count changes, the text inside the span will automatically update to reflect the new value.

If you open this HTML file in your browser, you should see the text “The current value of the count is: 0”. However, since we haven’t added any interactivity yet, the count will remain 0 and won’t change.

Under the p tag add the following code to create buttons that will increment and decrement the count:

    <button x-on:click="count++">Increment</button>
    <button x-on:click="count--">Decrement</button>

Here, we have added two buttons with the x-on:click directive. This directive listens for click events on the buttons and executes the specified JavaScript code when the buttons are clicked. The first button increments the count property by 1, while the second button decrements it by 1. Alpine automatically updates the text inside the span whenever the count property changes, so you will see the count value update in real-time as you click the buttons.

We have added fair amount of reactivity just by using few different Alpine directives, but this is still a very basic example and a lot of the time you might need to define more complex data or multiple properties. You can easily do this on the HTML page itself by adding comma separated values inside the x-data attribute like so:

<div x-data="{ count: 0, name: 'Pasindu', isVisible: true }">
    ...
</div>

Then we can refer the name property like this:

<h1>Hi, <span x-text="name"></span>!</h1> 

Using External Script Files
#

We could follow this pattern for any additional properties we want to define. But if we have a lot of data or methods to define, the x-data attribute can get quite long and bloated. To avoid this, we can define a separate script file and reference it in the x-data attribute.

Create a new JavaScript file named index.js in the same directory as your HTML file and reference it under the Alpine.js script tag like so:

<script src="index.js"></script>

Now, in the index.js file, we can add a event listener for the alpine:init event and define our component data and methods there:

document.addEventListener('alpine:init', () => {
  Alpine.data('counter', () => ({
    count: 0,
    name: 'Pasindu',
 
  }))
})

Here, we are using the Alpine.data method to define a new Alpine component named counter. Inside the component, we define our properties (count and name). These properties are same as before, but now they are defined in a separate JavaScript file. Now in the HTML file, we can reference this component in the x-data attribute like so:

<div x-data="counter">
    ...
</div>

Defining Functions in Alpine Component
#

Inside the counter component, we can define functions as well. Let’s define logCount function that logs the current count value to the console whenever it is called. Update the index.js file like so:

document.addEventListener('alpine:init', () => {
  Alpine.data('counter', () => ({
    count: 0,
    name: 'Pasindu',
    logCount() {
      console.log(`The current count is: ${this.count}`);
    }
  }))
})

Now, we can call this function whenever the count is incremented or decremented. Update the button elements in the HTML file like so:

    <button x-on:click="count++; logCount()">Increment</button>
    <button x-on:click="count--; logCount()">Decrement</button>

Now, whenever we click the increment or decrement buttons, the logCount function will be called, and the current count value will be logged to the console.

Hopefully now you can see how easy it is to get up and running with Alpine.js. In the next tutorial, we will start making our interactive web form and hooking that upto new data object.

Alpine.js Tutorial - This article is part of a series.
Part 1: This Article