I created a button that toggles the visibility of a div. It works fine the first couple of times, but then it stops working. When I click on column1, the hidden div inside column1 doesn't appear. But when I click on column2, the hidden div inside column2 does show up.
Apologies for my poor English, but I really want to understand why this is happening!
var tabList = document.querySelectorAll("li");
tabList.forEach(function(tab, index) {
tab.addEventListener('click', function() {
removeOther();
tab.classList.toggle("on");
btnEvent(tab);
});
});
function removeOther() {
for (var i = 0; i < tabList.length; i++) {
if (tabList[i].classList.contains("on")) {
tabList[i].classList.remove("on");
}
}
}
var btn = document.getElementsByTagName("button")[0];
function btnEvent(tab) {
var hiddenTabs = tab.querySelectorAll('.hidden');
btn.addEventListener("click", function() {
for (var i = 0; i < hiddenTabs.length; i++) {
hiddenTabs[i].classList.toggle("hidden");
}
})
}
div {
background: salmon;
width: 50px;
height: 50px;
margin: 5px;
display: none;
}
div.hidden,
li.on div.hidden {
display: none;
}
li.on div {
display: block;
}
<ul>
<li class="on">column1
<div>box</div>
<div>box</div>
<div>box</div>
<div class="hidden">box</div>
<div class="hidden">box</div>
<div class="hidden">box</div>
</li>
<li>column2
<div>box</div>
<div>box</div>
<div>box</div>
<div class="hidden">box</div>
<div class="hidden">box</div>
<div class="hidden">box</div>
</li>
<li>column3
<div>box</div>
<div>box</div>
<div>box</div>
<div class="hidden">box</div>
<div class="hidden">box</div>
<div class="hidden">box</div>
</li>
</ul>
<button>click!</button>