I have a dropdown menu and I am trying to toggle the display:block class on the ul child of the button, once that dropdown button is clicked. Currently the ul is set to display:none until the main button parent is clicked. So only the parent is shown on the screen currently.
I am having a hard time setting up these loops properly. I can set it up so when one button is clicked all the ul's for every project are shown but I only want the one under the corresponding button.
HTML:
<div class="dropdown"> <div class="project"> <button>website 1<i class="fas fa-caret-down"></i></button> <ul class="drop-list"> <li><a href="#">Live Website</a></li> <li><a href="#">Resources</a></li> </ul> </div> <div class="project"> <button>Website 2<i class="fas fa-caret-down"></i></button> <ul class="drop-list"> <li><a href="#">Live Website</a></li> <li><a href="#">Resources</a></li> </ul> </div> </div> JAVASCRIPT:
const projects = document.querySelectorAll('.project') const dropdown_lists = document.querySelectorAll('.drop-list') projects.forEach(button => button.addEventListener('click', function(){ // Feel like I need a forEach loop here to loop through the dropdown_lists or a reg for loop // for(i=0;i<dropdown_lists.length;i++) - maybe something like this // then I need to classList.toggle('active') on this ul // I'm getting stuck on how to make this in sync with the corresponding project button })) CSS:
.drop-list { display: none; } .active { display: block; } What I need is when projects[0] is clicked that toggles the class of 'active' to dropdown_lists[0] from the list. When projects[1] is clicked that toggles the class of 'active' to dropdown_lists[1] from the list.
Again, I can set up the code so when I click one button all the ul dropdown-lists toggle the class 'active' but I only want the first button to go with the first ul and second button with the second ul.
I'm just not sure how to go about this, either make a boolean if dropdown lists === 2 and project === 2 than toggle the class. I just cant think of the best practice to do this easily.
Appreciate the help.
Thanks
https://stackoverflow.com/questions/65730173/looping-through-parent-multiples-times-to-fire-correspoding-child-class January 15, 2021 at 11:37AM
没有评论:
发表评论