marius95
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
Marked As Solved
derek-zhou
I always use a named function for even handlers. With a anonymous function if you run the code twice you get two identical handlers.
Last Post!
marius95
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.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









