<popup-info>
๐ Using shadow DOM
๐ shadowRoot.innerHTML
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
Was this helpful?