Simple accordion doesn’t work because handler fires 2 times at once

I’m trying to create a very simple accordion.

index.html

    
    <div class="container">

        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio 
        </div>
        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio 
        </div>

    </div>

main.js

let accordians = document.querySelectorAll(".accordian")


const toggle = e => {
    if (e.target.nextElementSibling.classList.length < 2) {
        e.target.nextElementSibling.classList.add("hidden")
        console.log("1:",e.target.nextElementSibling.classList)
    }
    else {
        e.target.nextElementSibling.classList.remove("hidden")
        console.log("2:",e.target.nextElementSibling.classList)
    }
}

accordians.forEach((obj) => {
    obj.children[1].classList.add("hidden")
    obj.addEventListener('click', e => { toggle(e) }, false)
})

The first accordion works without any issue but when clicked one the second on the “toggle” function gets fired twice instantly making no difference. Any clue ?

Answer

First, you don’t need to write a toggle function for classList because it already exists.

Second, your <div class="body"> nodes need to have a closing </div> tag.

let accordians = document.querySelectorAll(".accordian")

accordians.forEach((obj) => {
    obj.children[1].classList.add("hidden")
    obj.addEventListener('click', e => {
      e.currentTarget.children[1].classList.toggle("hidden")
    }, false)
})
.hidden { display: none; }
<div class="container">

        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio </div>
        </div>
        <div class="accordian">
            <div class="title">Title</div>
            <div class="body">Lorem ipsum dolor, sit amet consectetur adipisicing elit. Corrupti mollitia maxime ab. Possimus est optio </div>
        </div>

    </div>

Leave a Reply

Your email address will not be published. Required fields are marked *