简体   繁体   中英

Remove all class active then toggle class - javascript

I'm trying to create a simple accordion, I've got the javascript working to toggle the class active on click of the item, but on the HTML i've already got the first item as active.

So basically I want it to work where you click other accordion header, the one that is open closes, and the one you clicked on opens.

I tried using classList.remove(active) before the toggle but threw and error.

Here is the link to what i've done so far:

var accordionLink = document.getElementsByClassName('accordion-item')
    for(var i = 0; i < accordionLink.length; i++) {
        var elem = accordionLink[i];
        elem.addEventListener('click', function(event){
            this.classList.toggle('active');
            event.preventDefault();
        }, false);
    }

https://codepen.io/anishpixellabs/pen/deNbKE

Any help would be great.

Regards

Have a look at this lines, I'm pretty sure something like this should work.

 var accordionLink = document.getElementsByClassName('accordion-item') for (var i = 0; i < accordionLink.length; i++) { var elem = accordionLink[i]; elem.addEventListener('click', function(event) { for (var j = 0; j < accordionLink.length; j++) accordionLink[j].classList.remove("active") this.classList.add('active'); event.preventDefault(); }, false); } 

Some explanations:

for (var i = 0; i < accordionLink.length; i++) {     // loop trough all elements to add "onClick event"
  var elem = accordionLink[i];                       // "elem" is current element
  elem.addEventListener('click', function(event) {   // adding "onClick" to current "elem"
    for (var j = 0; j < accordionLink.length; j++)   // ONCLICK trigger: "Loop trough all elements of 'accordionLink'
      accordionLink[j].classList.remove("active")    // remove the 'active class' for every occurrence of 'accordionLink'-class"
    this.classList.add('active');                    // add "active"-class to element that received ONCLICK-trigger
    event.preventDefault();
  }, false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM