<toast-message> 2 errors
by WebComponents
HTML
<!-- Example 1 -->
<toast-message></toast-message>
<h1>There are 2 errors in this code, can you fix them?</h1>
<script>
customElements.define('toast-message', class extends HTMLElement {
constructor() {
const createElement = (tag, props = {}) => Object.assign(document.createElement(tag), props);
super();
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;
}
`
})
);
}
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'
}
}));
</script>
<!-- Example 3 -->
<toast-message></toast-message>
<script>
setTimeout(() => {
window.dispatchEvent(new CustomEvent('toast-message', {
detail: {
message: 'Another message after 5 seconds'
}
}));
}, 5000);
</script>