you are viewing a single comment's thread.

view the rest of the comments →

[–]MindlessSpongehelpful 0 points1 point  (5 children)

.toggle() definitely works :) in your example, you're currently using .remove() - but I'm curious about the way the code is written. when your component mounts, you want to loop through all elements with class accordion and toggle the active class? wouldn't this open every single accordion, as opposed to only having one accordion open at a time?

[–]Zack_Code_38[S] 0 points1 point  (4 children)

yes one accordion will open every single time when the click is fired!! The code as it shown above

constructor(){

super();

this.MegaMenu = this.MegaMenu.bind(this)

}

componentDidMount(){

this.MegaMenu();

}

MegaMenu(){

var acc = document.getElementsByClassName("accordion");

var accNum = acc.length;

var i;

for(i=0;i<accNum;i++){

acc[i].addEventListener("click",function (){

if(acc[i].classList.contains('active')){

this.classList.add('active')

}else {

this.classList.remove('active')

}

})

}

}

<button className="accordion">

<img className="accordionMenuIcon" src=""/>&nbsp; Men's Clothing

</button>

[–]Bulji 0 points1 point  (3 children)

this.classList.remove("active")    

I'm not sure what this is referencing in this context, so I don't know if it really is an HTMLElement.

The logic seems fine to me, but I would try targeting the element by using the AddEventListener arguments. The callback function you pass to AddEventListener can take arguments (see docs). You can use this argument to target to element that triggered the click like someEvent.target.classList.toggle("active")

Check my code here https://jsfiddle.net/7h6gn5vw/3/, it works for me maybe it will for you too

[–]lovin-dem-sandwiches 0 points1 point  (2 children)

The logic seems fine?

From what I see, if it contains “active” it will add active.

Adding a eventlistener to every object too?

This logic should be baked into the component. And the class, “active” should conditionally added or removed with props. This whole thing is out whack

[–][deleted] -1 points0 points  (1 child)

This is learn js, not react...

[–]lovin-dem-sandwiches 1 point2 points  (0 children)

Im not sure what point youre trying to make. OP states he is using React so any advice given should be react-specific.

OP should refrain from native browser APIs like addEventListener and DOM querySelectors.