# Start Here
Create a blank HTML file somewhere on your computer with a name like: `i-love-alpine.html`
Using a text editor, fill the file with these contents:
```html
```
Open your file in a web browser, if you see `I ❤️ Alpine`, you're ready to rumble!
Now that you're all set up to play around, let's look at three practical examples as a foundation for teaching you the basics of Alpine. By the end of this exercise, you should be more than equipped to start building stuff on your own. Let's goooooo.
## Building a counter
Let's start with a simple "counter" component to demonstrate the basics of state and event listening in Alpine, two core features.
Insert the following into the `` tag:
```html
```
Now, you can see with 3 bits of Alpine sprinkled into this HTML, we've created an interactive "counter" component.
Let's walk through what's happening briefly:
### Declaring data
```html
```
Everything in Alpine starts with an `x-data` directive. Inside of `x-data`, in plain JavaScript, you declare an object of data that Alpine will track.
Every property inside this object will be made available to other directives inside this HTML element. In addition, when one of these properties changes, everything that relies on it will change as well.
Let's look at `x-on` and see how it can access and modify the `count` property from above:
### Listening for events
```html
```
`x-on` is a directive you can use to listen for any event on an element. We're listening for a `click` event in this case, so ours looks like `x-on:click`.
You can listen for other events as you'd imagine. For example, listening for a `mouseenter` event would look like this: `x-on:mouseenter`.
When a `click` event happens, Alpine will call the associated JavaScript expression, `count++` in our case. As you can see, we have direct access to data declared in the `x-data` expression.
> You will often see `@` instead of `x-on:`. This is a shorter, friendlier syntax that many prefer. From now on, this documentation will likely use `@` instead of `x-on:`.
### Reacting to changes
```html
```
`x-text` is an Alpine directive you can use to set the text content of an element to the result of a JavaScript expression.
In this case, we're telling Alpine to always make sure that the contents of this `span` tag reflect the value of the `count` property.
In case it's not clear, `x-text`, like most directives accepts a plain JavaScript expression as an argument. So for example, you could instead set its contents to: `x-text="count * 2"` and the text content of the `span` will now always be 2 times the value of `count`.
## Building a dropdown
Now that we've seen some basic functionality, let's keep going and look at an important directive in Alpine: `x-show`, by building a contrived "dropdown" component.
Insert the following code into the `` tag:
```html
Contents...
```
Toggle
If you load this component, you should see that the "Contents..." are hidden by default. You can toggle showing them on the page by clicking the "Toggle" button.
The `x-data` and `x-on` directives should be familiar to you from the previous example, so we'll skip those explanations.
### Toggling elements
```html
Contents...
```
`x-show` is an extremely powerful directive in Alpine that can be used to show and hide a block of HTML on a page based on the result of a JavaScript expression, in our case: `open`.
### Listening for a click outside
```html
Contents...
```
You'll notice something new in this example: `.outside`. Many directives in Alpine accept "modifiers" that are chained onto the end of the directive and are separated by periods.
In this case, `.outside` tells Alpine to instead of listening for a click INSIDE the `
`, to listen for the click only if it happens OUTSIDE the `
`.
This is a convenience helper built into Alpine because this is a common need and implementing it by hand is annoying and complex.
## Building a search input
Let's now build a more complex component and introduce a handful of other directives and patterns.
Insert the following code into the `` tag:
```html
```
- foo
- bar
- baz
By default, all of the "items" (foo, bar, and baz) will be shown on the page, but you can filter them by typing into the text input. As you type, the list of items will change to reflect what you're searching for.
Now there's quite a bit happening here, so let's go through this snippet piece by piece.
### Multi line formatting
The first thing I'd like to point out is that `x-data` now has a lot more going on in it than before. To make it easier to write and read, we've split it up into multiple lines in our HTML. This is completely optional and we'll talk more in a bit about how to avoid this problem altogether, but for now, we'll keep all of this JavaScript directly in the HTML.
### Binding to inputs
```html
```
You'll notice a new directive we haven't seen yet: `x-model`.
`x-model` is used to "bind" the value of an input element with a data property: "search" from `x-data="{ search: '', ... }"` in our case.
This means that anytime the value of the input changes, the value of "search" will change to reflect that.
`x-model` is capable of much more than this simple example.
### Computed properties using getters
The next bit I'd like to draw your attention to is the `items` and `filteredItems` properties from the `x-data` directive.
```js
{
items: ['foo', 'bar', 'baz'],
get filteredItems() {
return this.items.filter(
i => i.startsWith(this.search)
)
}
}
```
The `items` property should be self-explanatory. Here we are setting the value of `items` to a JavaScript array of 3 different items (foo, bar, and baz).
The interesting part of this snippet is the `filteredItems` property.
Denoted by the `get` prefix for this property, `filteredItems` is a "getter" property in this object. This means we can access `filteredItems` as if it was a normal property in our data object, but when we do, JavaScript will evaluate the provided function under the hood and return the result.
It's completely acceptable to forgo the `get` and just make this a method that you can call from the template, but some prefer the nicer syntax of the getter.
Now let's look inside the `filteredItems` getter and make sure we understand what's going on there:
```js
return this.items.filter( i => i.startsWith(this.search))
```
This is all plain JavaScript. We are first getting the array of items (foo, bar, and baz) and filtering them using the provided callback: `i => i.startsWith(this.search)`.
By passing in this callback to `filter`, we are telling JavaScript to only return the items that start with the string: `this.search`, which like we saw with `x-model` will always reflect the value of the input.
You may notice that up until now, we haven't had to use `this.` to reference properties. However, because we are working directly inside the `x-data` object, we must reference any properties using `this.[property]` instead of simply `[property]`.
Because Alpine is a "reactive" framework. Any time the value of `this.search` changes, parts of the template that use `filteredItems` will automatically be updated.
### Looping elements
Now that we understand the data part of our component, let's understand what's happening in the template that allows us to loop through `filteredItems` on the page.
```html
```
The first thing to notice here is the `x-for` directive. `x-for` expressions take the following form: `[item] in [items]` where `[items]` is any array of data, and `[item]` is the name of the variable that will be assigned to an iteration inside the loop.
Also notice that `x-for` is declared on a `` element and not directly on the `
`. This is a requirement of using `x-for`. It allows Alpine to leverage the existing behavior of `` tags in the browser to its advantage.
Now any element inside the `` tag will be repeated for every item inside `filteredItems` and all expressions evaluated inside the loop will have direct access to the iteration variable (`item` in this case).
## Recap
If you've made it this far, you've been exposed to the following directives in Alpine:
- x-data
- x-on
- x-text
- x-show
- x-model
- x-for
That's a great start, however, there are many more directives to sink your teeth into. The best way to absorb Alpine is to read through this documentation. No need to comb over every word, but if you at least glance through every page you will be MUCH more effective when using Alpine.
Happy Coding!
-----
# Essentials:
# Installation
There are 2 ways to include Alpine into your project:
- Including it from a `
```
> Don't forget the "defer" attribute in the `
```
That's it! Alpine is now available for use inside your page.
Note that you will still need to define a component with `x-data` in order for any Alpine.js attributes to work. See [https://github.com/alpinejs/alpine/discussions/3805](https://github.com/alpinejs/alpine/discussions/3805) for more information.
## As a module
If you prefer the more robust approach, you can install Alpine via NPM and import it into a bundle.
Run the following command to install it.
```terminal
$ npm install alpinejs
```
Now import Alpine into your bundle and initialize it like so:
```js
import Alpine from 'alpinejs' window.Alpine = Alpine Alpine.start()
```
> The `window.Alpine = Alpine` bit is optional, but is nice to have for freedom and flexibility. Like when tinkering with Alpine from the devtools for example.
> If you imported Alpine into a bundle, you have to make sure you are registering any extension code IN BETWEEN when you import the `Alpine` global object, and when you initialize Alpine by calling `Alpine.start()`.
> Ensure that `Alpine.start()` is only called once per page. Calling it more than once will result in multiple "instances" of Alpine running at the same time.
-----
# State
State (JavaScript data that Alpine watches for changes) is at the core of everything you do in Alpine. You can provide local data to a chunk of HTML, or make it globally available for use anywhere on a page using `x-data` or `Alpine.store()` respectively.
## Local state
Alpine allows you to declare an HTML block's state in a single `x-data` attribute without ever leaving your markup.
Here's a basic example:
```html
...
```
Now any other Alpine syntax on or within this element will be able to access `open`. And like you'd guess, when `open` changes for any reason, everything that depends on it will react automatically.
### Nesting data
Data is nestable in Alpine. For example, if you have two elements with Alpine data attached (one inside the other), you can access the parent's data from inside the child element.
```html
```
This is similar to scoping in JavaScript itself (code within a function can access variables declared outside that function.)
Like you may have guessed, if the child has a data property matching the name of a parent's property, the child property will take precedence.
### Single-element data
Although this may seem obvious to some, it's worth mentioning that Alpine data can be used within the same element. For example:
```html
```
### Data-less Alpine
Sometimes you may want to use Alpine functionality, but don't need any reactive data. In these cases, you can opt out of passing an expression to `x-data` entirely. For example:
```html
```
### Re-usable data
When using Alpine, you may find the need to re-use a chunk of data and/or its corresponding template.
If you are using a backend framework like Rails or Laravel, Alpine first recommends that you extract the entire block of HTML into a template partial or include.
If for some reason that isn't ideal for you or you're not in a back-end templating environment, Alpine allows you to globally register and re-use the data portion of a component using `Alpine.data(...)`.
```js
Alpine.data('dropdown', () => ({ open: false, toggle() { this.open = ! this.open }}))
```
Now that you've registered the "dropdown" data, you can use it inside your markup in as many places as you like:
```html
Content...
Some Other Content...
```
## Global state
If you wish to make some data available to every component on the page, you can do so using Alpine's "global store" feature.
You can register a store using `Alpine.store(...)`, and reference one with the magic `$store()` method.
Let's look at a simple example. First we'll register the store globally:
```js
Alpine.store('tabs', { current: 'first', items: ['first', 'second', 'third'],})
```
Now we can access or modify its data from anywhere on our page:
```html
...
```
# Templating
Alpine offers a handful of useful directives for manipulating the DOM on a web page.
Let's cover a few of the basic templating directives here, but be sure to look through the available directives in the sidebar for an exhaustive list.
## Text content
Alpine makes it easy to control the text content of an element with the `x-text` directive.
```html
```
Now, Alpine will set the text content of the `
` with the value of `title` ("Start Here"). When `title` changes, so will the contents of `
`.
Like all directives in Alpine, you can use any JavaScript expression you like. For example:
```html
```
The `` will now contain the sum of "1" and "2".
## Toggling elements
Toggling elements is a common need in web pages and applications. Dropdowns, modals, dialogues, "show-more"s, etc... are all good examples.
Alpine offers the `x-show` and `x-if` directives for toggling elements on a page.
### `x-show`
Here's a simple toggle component using `x-show`.
```html
Content...
```
Now the entire `
` containing the contents will be shown and hidden based on the value of `open`.
Under the hood, Alpine adds the CSS property `display: none;` to the element when it should be hidden.
This works well for most cases, but sometimes you may want to completely add and remove the element from the DOM entirely. This is what `x-if` is for.
### `x-if`
Here is the same toggle from before, but this time using `x-if` instead of `x-show`.
```html
Content...
```
Notice that `x-if` must be declared on a `` tag. This is so that Alpine can leverage the existing browser behavior of the `` element and use it as the source of the target `
` to be added and removed from the page.
When `open` is true, Alpine will append the `
` to the `` tag, and remove it when `open` is false.
## Toggling with transitions
Alpine makes it simple to smoothly transition between "shown" and "hidden" states using the `x-transition` directive.
> `x-transition` only works with `x-show`, not with `x-if`.
Here is, again, the simple toggle example, but this time with transitions applied:
```html
Content...
```
Let's zoom in on the portion of the template dealing with transitions:
```html
```
`x-transition` by itself will apply sensible default transitions (fade and scale) to the toggle.
There are two ways to customize these transitions:
- Transition helpers
- Transition CSS classes.
Let's take a look at each of these approaches:
### Transition helpers
Let's say you wanted to make the duration of the transition longer, you can manually specify that using the `.duration` modifier like so:
```html
```
Now the transition will last 500 milliseconds.
If you want to specify different values for in and out transitions, you can use `x-transition:enter` and `x-transition:leave`:
```html
```
Additionally, you can add either `.opacity` or `.scale` to only transition that property. For example:
```html
```
### Transition classes
If you need more fine-grained control over the transitions in your application, you can apply specific CSS classes at specific phases of the transition using the following syntax (this example uses [Tailwind CSS](https://tailwindcss.com/)):
```html
...
```
## Binding attributes
You can add HTML attributes like `class`, `style`, `disabled`, etc... to elements in Alpine using the `x-bind` directive.
Here is an example of a dynamically bound `class` attribute:
```html
```
As a shortcut, you can leave out the `x-bind` and use the shorthand `:` syntax directly:
```html