i wrote a JS code for my Website, which should show a modal and close it, if i click the "close" span. The first time, it worked perfectly. Here is the code:
var modal = document.getElementById("notifications");
var img = document.getElementById("shownotificationbar");
var span = document.getElementsByClassName("close")[0];
img.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
But the second time, the close button just dont work and i get
"Uncaught TypeError: Cannot set properties of null (setting 'onclick')"
Here is the second code piece:
var menu = document.getElementById("startmenu");
var img = document.getElementById("showstartmenu");
var span = document.getElementById("closemenu");
img.onclick = function() {
menu.style.display = "block";
}
span.onclick = function() {
menu.style.display = "none";
}
I think i can't use two spans, but what else should i do? Thank you very much!
CodePudding user response:
The second time img is null, so you cannot set img.onclick. The reason it is null is probably that there is no element with id showstartmenu, so when you are trying to get it (document.getElementById("showstartmenu")), you are getting null instead.
Edit:
Sorry, it could also be that span is null, for the same reason. I missed that one.
