Javascript Event Handler is firing twice

Hello everyone,

I try to use an Javascript Event Handler in my root.html.leex file.
Therefore I created a function in the app.js file:

const mainAccordion = document.getElementById("main-accordion");
mainAccordion.addEventListener("click", () => {
    const navigationWrapper = document.getElementById("navigation-wrapper");
    navigationWrapper.classList.toggle("nav-active")
});

Apparently when I put a log message inside the function I see that the function is fired twice in a row.

How to ensure that the function is only fired once?

Edit: Sorry for debugging purposes I change the method from toggle to add. It’s now changed back how it should be

Have you checked if you run the code more than once? Maybe you have added two event listeners.

I’m thinking it would also be helpful to post the relevant HTML here (meaning “main-accordion” and its contents). Googling this issue learns me that there are quite a few possible causes here :slight_smile:

Hey Marcus!

I use this code at one specific location. Nowhere else. I double checked it. There also isn’t another element with these IDs.

Not sure how to determine if I run the code more than once. I simply click on the div and the event is fired twice in a row.

You’re right! This is the whole html snippet:

<div id="main-accordion" class="md:hidden">
      <p>Some Text</p>
</div>

I always use a named function for even handlers. With a anonymous function if you run the code twice you get two identical handlers.

Ty for the ressource. I use a named function before but that didn’t fix the issue.

I had the same result with:

const toggleAccordion = () => {
    const navigationWrapper = document.getElementById("navigation-wrapper");
    console.log(navigationWrapper)
    navigationWrapper.classList.toggle("nav-active")
}

So I played around and read your article and I tried the following solution:


const toggleAccordion = (event) => {
    event.preventDefault()
    const navigationWrapper = document.getElementById("navigation-wrapper");
    console.log(navigationWrapper)
    navigationWrapper.classList.toggle("nav-active")
}

The event is triggered twice WITHOUT the event.preventDefault(). I don’t know why but it works.