I am trying to set up a web page where I have a list of buttons, and each button toggles the visibility of a div directly below it.
The problem I am having is that all of my buttons only toggle the visibility of the last div in my page.
Here is the following relevant code:
HTML
<div class="menuItem">
<button>Food Item</button>
<div class="info">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<img src="../images/menu/spaghetti.jpg" alt="spaghetti">
</div>
</div>
<div class="menuItem">
<button>Food Item</button>
<div class="info">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<img src="../images/menu/spaghetti.jpg" alt="spaghetti">
</div>
</div>
<div class="menuItem">
<button>Food Item</button>
<div class="info">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<img src="../images/menu/spaghetti.jpg" alt="spaghetti">
</div>
</div>
And here is my javascript:
"use strict";
(function() {
var menuItems = document.getElementsByClassName("menuItem");
for(var ii = 0; ii < menuItems.length; ii++) {
var button = menuItems[ii].getElementsByTagName("button")[0];
var info = menuItems[ii].getElementsByClassName("info")[0];
button.onclick = function() {
if(info.style.display === "block") {
info.style.display = "none";
} else {
info.style.display = "block";
}
};
}
})();
I don't think I totally understand what the javascript is doing under the hood. I think I'm getting references to each individual button, but it seems like when I change the onclick method for one button, I am changing the onclick method for all of them. Why is this happening, and how do I prevent this?