Back
An easy step-by-step tutorial on how to create a simple snackbar that disappears in 3 seconds.
<button onclick="openSnackbar()">Open snackbar</button> <div id="snackbar"> <span>Snackbar text...</span> </div>
function openSnackbar() { let snackbar = document.getElementById('snackbar') // Activate snackbar snackbar.classList.add('active') setTimeout(() => { // Deactivate snackbar (after 3000ms - 3 seconds) snackbar.classList.remove('active') }, 3000); }
#snackbar { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); margin: 10px; background-color: #333; padding: 10px 20px; width: 200px; border-radius: 5px; color: rgb(249, 129, 129); display: none; }Now we'll style the "active" class. This class will be added to our snackbar element when it should be displayed. To achieve that, we'll overwrite the display property and set it to block. Don't forget to add the "!important" rule, otherwise it won't be overrode since the id selectors have a higher specificity.
.active { display: block !important; }And that's it.
<button onclick="openSnackbar()">Open snackbar</button> <div id="snackbar"> <span>Snackbar text...</span> </div> <script> function openSnackbar() { let snackbar = document.getElementById('snackbar') snackbar.classList.add('active') setTimeout(() => { snackbar.classList.remove('active') }, 3000); } </script> <style> #snackbar { position: absolute; bottom: 0; left: 50%; transform: translateX(-50%); margin: 10px; background-color: #333; padding: 10px 20px; width: 200px; border-radius: 5px; color: rgb(249, 129, 129); display: none; } .active { display: block !important; } </style>Thank you for reading this article.