Tips and Tricks

Storing Variables Inside a Snippet

Setting a variable:

var variable_name = document.getElementById("input").value;

Getting a variable:

document.getElementById("output").innerHTML = variable_name;

Passing Variables Across Snippets

You can use "local storage" or "session storage" to easily pass variables between Snippets.

Session storage is only valid for a "session", e.g. until a tab is closed. Local storage is valid until it is cleared.

Setting session storage variable:

sessionStorage.variable_name = document.getElementById("input").value; 

Getting a session storage variable:

document.getElementById("output").innerHTML = sessionStorage.variable_name;

Setting a local storage variable:

localStorage.variable_name = document.getElementById("input").value; 

Getting a local storage variable:

document.getElementById("output").innerHTML = localStorage.variable_name;

Alpine.js

You can find a lot of good examples in the Alpine.js documentation.

Tabs:

<div x-data="{ tab: 'foo' }">
    <button :class="{ 'active': tab === 'foo' }" @click="tab = 'foo'">Foo</button>
    <button :class="{ 'active': tab === 'bar' }" @click="tab = 'bar'">Bar</button>

    <div x-show="tab === 'foo'">Tab Foo</div>
    <div x-show="tab === 'bar'">Tab Bar</div>
</div>

Toggle:

<div x-data="{ open: false }">
    <button @click="open = ! open">Toggle</button>

    <div x-show="open" @click.outside="open = false">Contents...</div>
</div>

Filter:

<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>

Counter:

<div x-data="{ count: 0 }">
    <button x-on:click="count++">Increment</button>

    <span x-text="count"></span>
</div>