Skip to content

Custom Elements

Brandon Jordan edited this page Nov 10, 2024 · 7 revisions

Custom elements

const myElement = new CustomElement('lazy-image');

Custom attributes

Extend the CustomElementAttribute class.

class ImageAttribute extends CustomElementAttribute {
    name = 'image';
    value;

    // The attribute was updated on the element.
    updated(oldValue, newValue) {
        //
    }

    // The attribute was added to the element.
    added(value) {
        //
    }

    // The value of the attribute has changed.
    changed(oldValue, newValue) {
        //
    }

    // The attribute was removed from the element.
    removed(oldValue) {
        //
    }
}

updated() is distinct from changed() as it is run anytime the attribute is added, changed, or removed.

Then, to use your custom attribute, you'll need to register it with your custom element.

myElement.registerAttribute('lazy-image', new ImageAttribute)

Get the value of an attribute.

myElement.getAttribute('image');

Register Elements

To use your custom element, use defineElements().

spark.defineElements(myElement);

Then include it in the HTML DOM.

<lazy-image image=""/>
Clone this wiki locally