I am new to javascript as you can understand from the code below. I wanted to create an event handler for the 6 buttons that I have on the page. When you click on the button, the display properties of the code block under the button change from "none" to "block". To do this, I needed to associate each button with one html section (in this case, tags with unique identifiers - pt1, pt2, etc.).
I struggled with this for a while and got the code below to work. And that is the problem! It turns out that I was still wrong. But as a newbie, when it worked, I thought I had done something. Since I spent several hours doing this, I need to know why the code below worked (so that I will feel like I learned something). I will highlight the part of the code that I can’t, for my life, training, why it worked.
var buttons = document.getElementsByClassName("CSS");
for (var i = 0; i < buttons.length; i++) {
var buttonID = "button" + i;
var clickHandlerID = "clickHandler" + i;
var buttonEH = document.getElementById(buttonID);
var clickHandler = window[clickHandlerID];
buttonEH.addEventListener("click", clickHandler, false);
}
function clickHandler1 () {
if (pt1.style.display === "block") {
pt1.style.display = "none";
} else {
pt1.style.display = "block";
}
}
function clickHandler2 () {
if (pt2.style.display === "block") {
pt2.style.display = "none";
} else {
pt2.style.display = "block";
}
}
source
share