I found this cool snackbar
which I can use on my test website for learning reasons.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_snackbar
This snackbar
uses ID so I will have to copy paste CSS
as well as javascript
over and over. if I want 4 different snackbar
on same page than I will have to copy paste CSS
code 4 times... that can be annoying.
So here is my attempt of setting multi snackbar
. you can copy paste my code in above link to see the results.
As you can see, the effect works but it loses the CSS
code. Any idea?
again: In snackbar
id... I'm just creating layout of box, so I can change snackbar
to class... and have id for unique box.
<!DOCTYPE html>
<html>
<head>
<style>
.snackbar {
visibility: hidden;
min-width: 250px;
margin-left: -125px;
background-color: #333;
color: #fff;
text-align: center;
border-radius: 2px;
padding: 16px;
position: fixed;
z-index: 1;
left: 50%;
bottom: 30px;
font-size: 17px;
}
.snackbar.show {
visibility: visible;
-webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
animation: fadein 0.5s, fadeout 0.5s 2.5s;
}
@-webkit-keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@keyframes fadein {
from {bottom: 0; opacity: 0;}
to {bottom: 30px; opacity: 1;}
}
@-webkit-keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
@keyframes fadeout {
from {bottom: 30px; opacity: 1;}
to {bottom: 0; opacity: 0;}
}
</style>
</head>
<body>
<h2>Snackbar / Toast</h2>
<p>Snackbars are often used as a tooltips/popups to show a message at the bottom of the screen.</p>
<p>Click on the button to show the snackbar. It will disappear after 3 seconds.</p>
<button onclick="myFunction()">Show Snackbar</button>
<div id="myUniqueBar" class="snackbar">Some text some message..</div>
<script>
function myFunction() {
var x = document.getElementById("myUniqueBar")
x.className = "show";
setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
</script>
</body>
</html>
Because you are removing your existing snackbar class when using the code:
x.className = "show";
Instead replace the above code with this code:
x.classList.add("show");
Codepen link: https://codepen.io/anon/pen/KZRJmP