I have a small class with which I can make and display an alert. The duration of the alert and the content is given to the class via a class function and controlled.
When I trigger the toast it is shown and hidden again correctly after the durationTime. But then the alert appears again and is hidden again shortly afterwards. In no part of the code do I call the alert twice.
Question: I suppose this could be related to the context and the timeset. But I have little experience with this. Can someone please help me? Thanks in advance! Max
class ToastHawaii {
constructor(config = {}) {
this.duration = typeof(config.duration) == 'undefined' ? 1000 : config.duration;
this.toastContainer = config.toastContainer;
}
makeToast(d) {
const html = `<div class="toast">
<div>${d.title}</div>
<div class="right">${d.content}</div>
</div>`;
this.toastContainer.innerHTML = html;
this.toastContainer.classList.add("show");
setTimeout(() => {
this.toastContainer.classList.remove("show");
}, this.duration);
}
}
const mA = new ToastHawaii({
duration: 4000,
toastContainer: document.querySelector('#myAlertContainer')
});
const content = `ICON`;
document.querySelector("button").addEventListener('click', () => {
mA.makeToast({
title: "hello",
content: content
});
})
#myAlertContainer {
position: fixed;
left: 0%;
top: 30px;
visibility: hidden;
width:100%;
z-index: 1;
height:60px;
}
.toast {
box-sizing: border-box;
display: flex;
justify-content: space-between;
align-items: center;
border-radius: 8px;
background: gray;
color: #000;
height:100%;
padding: 0 16px;
font-size: 0.8rem;
font-weight: bold;
margin: 0 auto;
max-width: 350px;
}
.right {
display: flex;
gap: 5px;
align-items: center;
}
#myAlertContainer.show {
visibility: visible;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@-webkit-keyframes fadein {
from {top: 0; opacity: 0;}
to {top: 30px; opacity: 1;}
}
@keyframes fadein {
from {top: 0; opacity: 0;}
to {top: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {top: 30px; opacity: 1;}
to {top: 0; opacity: 0;}
}
@keyframes fadeout {
from {top: 30px; opacity: 1;}
to {top: 0; opacity: 0;}
}
<div id="myAlertContainer"></div>
<button>makeAlert!</button>
<h1>hello</h1>
<p>lorem ipsum</p>