Reputation: 400
Was trying to add a toast message that would pop up when i call a function, however, i am getting the below errors:
Uncaught TypeError: Cannot read property 'classList' of null at showSnackbarMessage
When i run it on y local browser, i get an error on my console that classList is empty, however, the code seems to be working here
function showSnackbarMessage(message, time) {
let snackbar_Div = document.getElementById('snackbar');
snackbar_Div.classList.add("show");
snackbar_Div.innerHTML = message;
time=time*1000;//time is in seconds
// After 2 seconds, remove the show class from DIV
setTimeout(function(){ snackbar_Div.classList.remove("show")}, time);
};
showSnackbarMessage('Welcome to the page', 2);
#snackbar {
visibility: hidden; /* Hidden by default. Visible on click */
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;
}
#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;}
}
/*---------- End of snackbar ----------------*/
<div id="snackbar">Some text some message..</div>
Upvotes: 0
Views: 478
Reputation: 628
The div has not loaded on the DOM and your method is called before that. classList is not empty, Javascript is just not able to find the element because it doesn't exist on the DOM.
Try calling showSnackbarMessage on window.onload
Upvotes: 1