DEV Community

loading...
Cover image for Alpine hands on: simple countdown

Alpine hands on: simple countdown

benbao profile image Benjamin Bromberg ・2 min read

Alpine.js is a minimalist JavaScript framework aiming to bring the convenience of reactive and declarative programming, known from full fledged frameworks like React, with a much smaller footprint.

LogRocket published a good starting point if this is your first time hearing about Alpine.js and a previous article of mine on Animations with Alpine.js is here on dev.

Countdown with Alpine.js

While the framework focuses on only few directives these unlock a great power to comfortably and quickly build interactivity into your websites.

With a simple countdown as example app we can see how Alpine.js enables us to read data from the DOM and react to events, all while keeping our HTML connected to the JavaScript.

To illustrate that I have created a simple form taking a number input to start our countdown from, like so:
Form with Alpine.js

x-data

Right on the first element we define our variables with the x-data attribute. This is like setting javascript variables with var or let. Values from x-data are available in all child nodes.

x-show

This directive allows us to control the visibility of an element based on the provided boolean value.

@submit.prevent

This command actually combines a lot of helpful actions. The @ is an alias for on-, which allows us to capture events, in this case the form submit event.

With the modifier prevent we let Alpine.js take care of the default event behaviour, similar to what event.preventDefault() would do in vanilla JS.

As we can write any valid JavaScript code in our directives I use the event handler to set the active status to true, read the countdown start value from our input with $refs and start the countdown through setInterval.

x-ref

This sets a reference to the node, which allows us to access it with the global $refs variable later on in the code.

Now onto our actual countdown:
Countdown with Alpine.js

Again we are using the x-show directive to control visibility of our form or the countdown elements.

x-if

This is similar to x-show but can only be applied to template elements. With the if directive we can control what elements will be rendered, rather than just setting the display value.

x-text

Alpine.js also provides a convenient way to set the text and html property of nodes with the respective directives. This will set the content to the value of the variable passed into the directive.

A live example of the complete code is available on JSFiddle.

Code images are generated with carbon.

Cover photo by Sarah Pflug.

Discussion (0)

Forem Open with the Forem app