Issue
I have the code below in my index.php, only the first item in the accordion shows. For instance: when I click on Status or Repeated, am expecting the sub-menu of the clicked item but instead I get the result from the first list. That is Position.
<style>
ul .sub_main{
cursor: pointer;
}
.nested {
display: none;
}
.active {
display: block;
}
</style>
<ul class="sidebar-menu" data-widget="tree">
<li class="header">MANAGE</li>
<li class="sub_main"><i class="fa fa-users"></i><span>Positions</span><i class="fa fa-plus" aria-hidden="true"></i>
<ul class="nested">
<li class=""><a href="#"><i class="fa fa-users"></i> <span>a link 1</span></a></li>
<li class=""><a href="#"><i class="fa fa-users"></i> <span>a link 2</span></a></li>
</ul>
</li>
<li class="sub_main"><i class="fa fa-tasks"></i> <span>Status</span><i class="fa fa-plus" aria-hidden="true"></i>
<ul class="nested">
<li class=""><a href="#"><i class="fa fa-tasks"></i> <span>b link 1</span></a></li>
<li class=""><a href="#"><i class="fa fa-tasks"></i> <span>b link 2</span></a></li>
<li class=""><a href="#"><i class="fa fa-tasks"></i> <span>b link 3</span></a></li>
</ul>
</li>
<li class="sub_main"><i class="fa fa-tasks"></i> <span>Repeated</span><i class="fa fa-plus" aria-hidden="true"></i>
<ul class="nested">
<li class=""><a href="#"><i class="fa fa-tasks"></i> <span>c link 1</span></a></li>
<li class=""><a href="#"><i class="fa fa-tasks"></i> <span>c link 2</span></a></li>
</ul>
</li>
</ul>
this is the script to show the accordion item when clicked.
var toggler = document.getElementsByClassName("sub_main");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
});
}
Solution
Your JS line with the class toggle method is being called on the parent of the "sub-main" class. This means that the querySelector is grabbing the first ".nested" element it finds from your ul.sidebar-menu element, which will always be the top ".nested" group.
If you simply remove the "parentElement" from that JS line, then the querySelector will look for the first ".nested" within the ".sub-main" (this) element.
Your JS should look like:
var toggler = document.getElementsByClassName("sub_main");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.querySelector(".nested").classList.toggle("active");
});
}
Answered By - PsyenceIO
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.