There are huge amount of Javascript libraries and frameworks available for us to use with different features, countless coming every month. Yet I am presenting you with another one called Alpine.js. It has potential to replace Jquery. It’s quite similar to jquery and Vue.js, but it’s much smaller and much more powerful. We will learn about them soon. Creator of Alpine.js recently launched a new version named V3.
What are we going to learn in this tutorial?
- What is Alpine.js?
- What are the advantages of Alpine.js over others?
- Is this framework for me?
- Why we call it tailwind of JS? Is it being used by Tailwind?
- Difference between Alpine and Jquery?
- Can we use it like jQuery?
- Why Alpine.js is so small in size while comparing to Vue.js?
- Guides
- Install Alpine.js
- Basic concepts
- x-data
- x-show
- x-if
- x-for
- x-on
- x-model
- x-text
- x-html
- x-bind
- x-cloak
- x-init
- x-transition
- x-ref
- x-effect
- x-ignore
- Magic properties
- $watch
- $el
- $refs
- $store
- $dispatch
- $nextTick
- Demo
- Conclusion
- References
What is Alpine.js?
Alpine.js is a javascript framework which let us enhance our javascript applications with it’s reactive and declarative features. It is not used to create SPAs, is just uses Angular.js like approach.
The main power of Alpine.js is it’s reactive and declarative nature. If you are familiar with Angular.js or Vue.js, you will understand Alpine.js very easily. It is also a DOM manipulation framework. It makes it easy to manipulate DOM elements in a declarative way with very little code. Much less than what we can do using Vanilla JS or jQuery. Same can be achieved using Angular.js or React.js but there size is much bigger.
Let’s see some statements about Alpine.js from other creators and developers.
Alpine is a rugged, minimal tool for composing behavior directly in your markup.
Alpine.js offers you the reactive and declarative nature of big frameworks like Vue or React at a much lower cost. You get to keep your DOM and sprinkle in behavior as you see fit. - Alpine.js docs on the Github readme
I hope you find Alpine to be a breath of fresh air. Silence among noise. - Caleb Porzio(Alpine.js’s Creator)
What are the advantages of Alpine.js over others?
- Alpine.js contains the power of big frameworks with small bundle size. Alpine 9.19KB Gzipped, Jquery 24.46KB Gzipped, Vue.js 34.15KB Gzipped at the time of writing this blog.
- Events like click, mouseover, mouseout, keydown, keyup, keypress, focus, blur, change, input, submit, etc. are all available in Alpine.js.
- x-data and x-show are the most powerful features of Alpine.js.
Is this framework for me?
Here are few points.
- If you are totally new to javascript, it’s totally for you.
- If you are familiar with Angular.js or Vue.js, it’s for you.
- If you think jquery is easy to use then you should try Alpine.js. Syntax are almost same.
- If you are familiar with Tailwind CSS, it’s for you.
So the conclusion is that if you are still with me than Alpine.js is for you.
Why we call it tailwind of JS? Is it being used by Tailwind?
No, but Tailwind CSS and Alpine.js share common approach. Actually Alpine is inspired by Tailwind CSS. And it was previuosly called “Tailewind of JS”. Like Tailwind CSS, We don’t need extra files to write JS code. It is packed with enough utility classes that can be embedded in any design. Alpine has 15 directives.
Difference between Alpine and Jquery?
- Alpine is reactive but jquery is not.
- Alpine is smaller in size than jquery. Alpine 9.19KB while jquery 24.46KB.
- Alpine uses reactivity for data binding. Jquery uses event delegation for data binding.
Can we use it like jQuery?
Jquery and Alpine.js both do the same thing, but jquery works from javascript, while Alpine.js works from HTML. Alpine simplifies the DOM manipulation and makes it easier to write declarative code. So it can’t be used like jQuery.
For Example here is the Code for opening a modal using Alpine.js and Jquery.
Why Alpine.js is so small in size while comparing to Vue.js?
Vue.js and Alpine.js APIs are same. We can bind data using x-data in alpine and v-data in vue.js. Alpine is smaller because it uses declarative approach and leverages the power of reactivity. So extra code was shaved off.
Guides
Install Alpine.js
Alpine.js can be installed using npm or yarn. We can also use CDN.
CDN
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
Add this line at the end of your head tag. While in production you should also quote specific version number to avoid unnecessary issues.
Like this
<script defer src="https://unpkg.com/alpinejs@3.7.1/dist/cdn.min.js"></script>
NPM
It can also be installed using NPM. To install Alpine.js, run the following command in your terminal.
npm install i alpinejs
and then import it in your code.
import 'alpinejs'
Basic concepts
Alpine.js contains 15 directives. They are: x-data, x-show, x-if, x-for, x-on, x-model, x-text, x-html, x-bind, x-on, x-cloak, x-ref, x-ignore, x-effect, x-transition.
Contains 6 magic properties: $watch, $el, $refs, $store, $dispatch, $nextTick.
Also contains 2 methods: Alpine.store and Alpine.data.
x-data
Declare a new Alpine component and its data for a block of HTML. This directive is used to declare data in a component. Also defines scope of the component. The data is an object literal with it’s properties available in the component scope.
syntax
<div x-data="JSON data"></div>
example
<div x-data="{ name: 'John' }">
<p>Hello <b x-text="name"></b></p>
</div>
Here name
variable is available in scope of div. It can be referenced in the component using x-text
directive. It can also be referenced by another div or component using __x
property. See here for more details.
x-show
This directive is used to show or hide (Toggle) a block of HTML. Can be used with or without data. Takes a boolean value.
syntax
<div x-show="boolean value"></div>
example
<div x-data="{show: false }">
<div x-show="show">
<p>Hello <b x-text="name"></b></p>
</div>
<button x-on:click="show = !show "> Toggle Show </button>
</div>
x-if
x-if, conditionally add or remove a block of HTML from the page. Takes a boolean value. Template tags should be used to render the data.
syntax
<template x-if="boolean value"></template>
example
<template x-if="open">
<div>...</div>
</template>
x-for
x-for, repeats a block of HTML multiple times based on data set. Takes an array of data. Template tags should be used to render the data.
syntax
<template x-for="item in items"></template>
example
<div x-data="{ items: ['John', 'Jane', 'Joe'] }">
<ul>
<template x-for="item of items">
<p x-text="item"></p>
</template>
</ul>
</div>
x-on
x-on, Listens for browser events, and run a needed code.
syntax
<div x-on:[event]="[expression]"></div>
example
<div x-on:click="alert('Hello')">Alert Hello</div>
Events can be keydown, keyup, keypress, click, mouseover, mouseout, focus, blur, change, input, submit, etc.
x-model
x-model, binds the value of an input to a variable in the component. It syncs the value of the input with the variable.
syntax
<input x-model="variable">
example
<div x-data="{ search: '' }">
<input type="text" x-model="search">
Searching for: <p x-text="search"></p>
</div>
x-text
x-text, binds the value of an element to a variable in the component. It syncs the value of the element with the variable.
syntax
<p x-text="variable"></p>
example
<div x-data="{ search: '' }">
<input type="text" x-model="search">
Searching for: <p x-text="search"></p>
</div>
x-html
x-html, sets the innerHTML of an element. It can be used to render the data.
syntax
<p x-html="variable"></p>
x-bind
x-bind, dynamically sets HTML attributes of an element.
example
<div x-bind:class="! open ? 'hidden' : ''">
...
</div>
x-cloak
x-cloak, hides the element until the alpine.js finished initializing it’s content. Can be used to hide a model while page’s intial loading.
syntax / example
<div x-cloak>
Something to be hidden at the time of initializing.
</div>
x-ref
x-ref, sets an element as a reference. It can be referenced using $refs
property.
example
<input type="text" x-ref="myRef">
<button x-on:click="navigator.clipboard.writeText($refs.myRef.value)">
Copy
</button>
x-ignore
x-ignore, prevents Alpine.js from rendering/initializing the a block of HTML.
example
<div x-ignore>
Should not be rendered.
</div>
x-effect
x-effect, execute a script each time one of its dependancies change.
example
<div x-effect="console.log('Count is '+count)"></div>
x-transition
x-transition, transition an element in and out using CSS transitions.
example
<div x-show="open" x-transition>
...
</div>
x-init
x-init, executes a script when the component is initialized by alpine.js.
example
<div x-init="console.log('Component initialized'); date=new Date()"></div>
Magic properties
There are total of 6 properties that can be used to do various things.
$watch
$watch, listens for changes in the data and runs a callback function when the data changes.
example
<div
x-data="{ count: 1 }"
x-init="$watch('count', value => console.log('count is ' + value))"
>
<button x-on:click="count++">Increase Count</button>
</div>
Imagine what we can do with this.
$refs
$refs, contains or hold the references of all the elements which were tagged by x-ref in DOM.
<div x-ref="name">Rahul</div>
<div x-ref="age">25</div>
Now we can reference these elements using $refs anytime.
<button x-on:click="console.log($refs.name.innerHTML)"> Click Me </button>
$el
$el, accesses and references the current DOM element.
example
<div x-init="new Pikaday($el)"></div>
$store
$store, accesses a global store registered using Alpine.store(…)
<h1 x-text="$store.site.title"></h1>
$dispatch
$dispatch is used to dispatch custom browser events from the current elements.
<div x-on:test="...">
<button x-on:click="$dispatch('test')"> Dispatch Test Event </button>
</div>
$nextTick
It waits until the next ‘tick’ (browser repaint) and then runs the code.
<div x-data="{ btn: true }">
<button
x-on:click="
btn = !btn ;
$nextTick(() => {
console.log($event.target.innerText)
});"
x-text="btn"
></button>
</div>
Demo
Now, it’s time to show you some of the things you can do with Alpine.js pretty easily.
Search using Alpine.js
You just need to insert this code into your <body>
tag (ofcourse, after installing Alpine.js).
<div
x-data="{
search: '',
items: ['foo', 'bar', 'baz'],
get filteredItems() {
return this.items.filter(
i => i.startsWith(this.search)
)
}
}"
>
<input x-model="search" placeholder="Search...">
<ul>
<template x-for="item in filteredItems" :key="item">
<li x-text="item"></li>
</template>
</ul>
</div>
Taken from Alpine.js docs.
It will be able to filter the items based on the search term you type, right on the browser without any lag.
Conclusion
We learned a lot about the power of Alpine.js. We started from powers of Alpine, then moved towards installing Alpine.js, then basics of Alpine.js, then advanced features of Alpine.js. Alpine.js is a powerful framework that can be used to build complex web applications with very small fingerprints.
I would definitely recommend you to check out Alpine.js. Let me know in comments which directives you would like to use first.
Note: This is not complete guide. I will be adding more things and demos. I have not covered all the directives or magic properties, I just covered the most important ones.
As Always if you have any comments or suggestions, please let me know via comments. If you have any questions, please feel free to ask me.
If you like this post, share it with your friends, employees, employer and colleagues. Happy Coding! Bye 👋
References
Cover Image Reference: Alpine.js Cover image
Alpinejs.dev
- Start here Alpine.js https://alpinejs.dev/start-here
- Alpine.js Website https://alpinejs.dev/
github.com
- GitHub — alpinejs/alpine: A rugged, minimal framework for composing JavaScrict behavior in your markup. https://github.com/alpinejs/alpine
tailwindcss.com
- Tailwind CSS https://tailwindcss.com/
smashingmagazine.com
- Introducing Alpine.js: A Tiny JavaScript Framework https://www.smashingmagazine.com/2020/03/introduction-alpinejs-javascript-framework/
daily.dev
- Getting started with Alpine.js https://daily.dev/blog/alpine-js-the-ultimate-guide
Ohh you made it to the end. Thank you for reading. Bye 👋