Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

Reusable Alpine.js components

<template x-component="dropdown">
    <div x-data="{ ...dropdown(), ...$el.parentElement.data() }">
        <button x-on:click="open">Open</button>

        <div x-show="isOpen()" x-on:click.away="close" x-text="content"></div>
    </div>
</template>

<x-dropdown content="Content for my first dropdown"></x-dropdown>

<div> Random stuff... </div>

<x-dropdown content="Content for my second dropdown"></x-dropdown>

<x-dropdown></x-dropdown>

<script>
    function dropdown() {
        return {
            show: false,
            open() { this.show = true },
            close() { this.show = false },
            isOpen() { return this.show === true },
            content: 'Default content'
        }
    }

    // The pure client-side code
    document.querySelectorAll('[x-component]').forEach(component => {
        const componentName = `x-${component.getAttribute('x-component')}`
        class Component extends HTMLElement {
            connectedCallback() {
                this.append(component.content.cloneNode(true))
            }
 
            data() {
                const attributes = this.getAttributeNames()
                const data = {}
                attributes.forEach(attribute => {
                    data[attribute] = this.getAttribute(attribute)
                })
                return data
            }
        }
        customElements.define(componentName, Component)
    })
</script>
Comment

PREVIOUS NEXT
Code Example
Javascript :: js changing selected option by index 
Javascript :: sweetalert question 
Javascript :: how to insert with variables from js to mysql 
Javascript :: how to use if else inside jsx in react 
Javascript :: buffer nodejs 
Javascript :: pop up notification using jquery 
Javascript :: remove trailing zeros javascript 
Javascript :: javascript array flatten 
Javascript :: how to comment out code in react js 
Javascript :: javascript check if in array 
Javascript :: remove array item with index 
Javascript :: delete file with deno 
Javascript :: js get all object keys 
Javascript :: discord button 
Javascript :: js setinterval vs settimeout 
Javascript :: javascript array.isarray 
Javascript :: js array random 
Javascript :: how to get current date in express js 
Javascript :: get role id from role position 
Javascript :: react algolia range slider 
Javascript :: javascript remove last charter stings 
Javascript :: javascript how to merge arrays 
Javascript :: vuejs v-model select 
Javascript :: vue js readdir 
Javascript :: jspdf reduce size file 
Javascript :: Accessing Object Properties with Variables 
Javascript :: foeach in js 
Javascript :: Using Then To Create A Promise In JavaScript 
Javascript :: parsley validation checkbox 
Javascript :: js any 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =