Alpine JS : An Intro
Topics
- Overview
- How to Code
- Creating a basic button
Overview
Your new, lightweight, JavaScript framework. -Alpine Js
It is a light weight js framework inspired by Vue JS!
How To Code
For it you have this script tag --
<script src="https://unpkg.com/alpinejs" defer></script>
but in the site it will be showing like this
<script src="//unpkg.com/alpinejs" defer></script>
just add https: before //unpkg.com
so for writing code just add the script tag inside the head tag
<head> <title>Title</title> <script src="https://unpkg.com/alpinejs" defer></script> </head>
Now in the body tag add a attribute like this
<body x-data="data()"></body>
Now add another script tag! And write the following inside it!
<body x-data="data()"> <script> function data(){ return{ } } </script> </body>
Now understand what was data() it would fetch all the data from here.
So becoz it is an object so add variables like this varName : "value"
Creating a basic button
So lets create some variables!
<script> function data(){ return{ shown : false, click(){ }, } } </script>
Here there is a var called shown with false as its value, and a function named click() so lets code them all.
<button>Toggle</button> <div>Content</div>
Add these.
Give a attribute x-show="shown"
to the div. (x-show means if the value is being shown or not [it is an if statement], it goes away[the button] because the var shown is false if it is true the button will be visible).
Now give a attribute x-on:click="click()"
to the button (it will run when the button is clicked).
Coding the function.
click(){ this.shown = !this.shown },
Now it will toggle the shown var as true and then false!
Enjoy!
All the code :-
<head> <title>Title</title> <script src="https://unpkg.com/alpinejs" defer></script> </head> <body x-data="data()"> <button x-on:click="click()">Toggle</button> <div x-show="shown">Content</div> <script> function data(){ return{ shown : false, click(){ this.shown = !this.shown }, } } </script> </body>
Consider Following??
Top comments (0)