Nowadays, Pop-up or Toast notifications are used in almost all apps. A toast notification shows information that appears on some action performed and disappears after some time.
Let's start with a button to show a toast message
<div id="container"></div>
<button id="btn">Show Notification</button>
and put the style for the button
button {
background-color: lightblue;
padding: 1rem;
border-radius: 5px;
color: darkblue;
border: none;
font-family: inherit;
cursor: pointer;
}
Now get the button element and attach the click function to it
const btn = document.getElementById("btn");
const container = document.getElementById("container");
btn.addEventListener("click", () => {
generateToast();
});
let's write the actual toast code now
function generateToast() {
//creating toast element and adding styling class
const toast = document.createElement("div");
toast.classList.add("toast");
//assigning random background color to each toast
var randomColor = Math.floor(Math.random() * 16777215).toString(16);
toast.style.backgroundColor = "#" + randomColor;
//assigning text to toast
toast.innerText = "Hello there 👋🏼";
container.appendChild(toast);
//making toast disappear after 2s
setTimeout(() => {
toast.remove();
}, 2000);
}
Also, add some nice styling to toast with animation
#container {
position: fixed;
bottom: 10px;
right: 10px;
}
.toast {
padding: 1rem;
border-radius: 5px;
margin: 10px;
color: rgb(0, 0, 58);
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@keyframes fadein {
from {
bottom: 0;
opacity: 0;
}
to {
bottom: 30px;
opacity: 1;
}
}
@keyframes fadeout {
from {
bottom: 30px;
opacity: 1;
}
to {
bottom: 0;
opacity: 0;
}
}
Conclusion
Thank you for reading!
Feel free to connect on Twitter