<popup-info>

About using external CSS styles

Note that <link> elements do not block paint of the shadow root, so there may be a flash of unstyled content (FOUC) while the stylesheet loads.

/*
    Using Shadow DOM
    https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_shadow_DOM
*/

// ⭐️ 1. custom web component
class PopUpInfo extends HTMLElement {

    // constructor
    constructor() {

        // tell HTMLElement to initialize itself.
        super();

        // Create a shadow root
        let shadow = this.attachShadow({mode: 'open'});

        // get attributes from this <popup-info>
        let info = this.getAttribute('data-text');
        let src = this.getAttribute('img') ?? 'https://mdn.github.io/web-components-examples/popup-info-box-web-component/img/alt.png';

        // set the shadow tree
        shadow.innerHTML = PopUpInfo.template(src, info);
        
    }

    // template HTML (⭐️ external css styles)
    static template(imgURL, infoText){
        return `
            <link href="popup.css" rel="stylesheet" />

            <span class="wrapper">
                <span class="icon" tabindex=0>
                    <img src="${imgURL}">
                </span>
                <span class="info">${infoText}</span>
            </span>
        `;
    }

} 

// ⭐️ 2. define custom tag <popup-info>
// ⭐️⭐️ custom element names must contain a "hyphen".
customElements.define('popup-info', PopUpInfo);

Last updated