<toast-message>
by WebComponents
HTML
<!-- Example 1 -->
<toast-message></toast-message>
<script>
// CREATEELEMENT NOW AVAILABLE TO THE WHOLE FILE
const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
customElements.define('toast-message', class extends HTMLElement {
constructor() {
// EXTRA super() CALL DELETED
super().attachShadow({
mode: 'open'
}).append(
createElement('style', {
innerHTML: `:host {
position: fixed;
bottom: 10px;
right: 10px;
display: grid;
gap: 10px;
}
.toast {
background: #333;
color: #fff;
padding: 10px;
border-radius: 5px;
opacity: 1;
transition: opacity 0.5s ease;
}
.fade-out {
opacity: 0;
}`
}),
createElement("div",{
onclick: this
})
);
}
handleEvent
connectedCallback() {
this.handleToast = this.handleToast.bind(this);
window.addEventListener('toast-message', this.handleToast);
}
disconnectedCallback() {
window.removeEventListener('toast-message', this.handleToast);
}
handleToast(event) {
const message = event.detail.message;
const toast = this.shadowRoot.appendChild(createElement('div', {
className: 'toast',
innerHTML: message
}));
setTimeout(() => {
toast.classList.add('fade-out');
setTimeout(() => this.shadowRoot.removeChild(toast), 500);
}, 10000);
}
});
</script>
<!-- Example 2 -->
<toast-message></toast-message>
<script>
window.dispatchEvent(new CustomEvent('toast-message', {
detail: {
message: 'This is a test message'
...