Crucifix Arnaud

Web Components

The basics

JavaScript:

class HelloWorld extends HTMLElement {
    static observedAttributes = ["name"];

    constructor() {
        super();

        this.name = "World";
    }

    attributeChangedCallback(name, oldValue, newValue) {
        this.name = newValue;
        this.render();
    }

    connectedCallback() {
        this.render();
    }

    render() {
        this.textContent = `Hello ${this.name}!`;
    }
}

customElements.define("hello-world", HelloWorld);


Html:

<hello-world name="Blaise"></hello-world>

Result:

Simple Card

JavaScript:

class SimpleCard extends HTMLElement {
    static observedAttributes = ["name"];

    constructor() {
        super();

        this.name = "World";
        this.shadow = this.attachShadow({ mode: 'closed' });
    }

    attributeChangedCallback(name, oldValue, newValue) {
        this.name = newValue;
        this.render();
    }

    connectedCallback() {
        this.render();
    }

    render() {
        this.shadow.innerHTML = "";

        const template = document.getElementById('simple-card')
            .content.cloneNode(true);

        const nameElement = template.querySelector(".simple-card-name")

        nameElement.textContent = this.name;

        this.shadow.append( template );
    }
}

customElements.define("simple-card", SimpleCard);

Html:

<template id="simple-card">
    <style>
        .card {
            padding: 1rem;
            border: 1px solid var(--color-text);
            border-radius: 3px;
            display: flex;
        }
        p {
            margin: 0;
        }
    </style>
    <div class="card">
        <p>Name: <span class="simple-card-name"></span></p>
    </div>
</template>

<simple-card name="Blaise"></simple-card>

Result:

Links