DEV Community

Cover image for JavaScript addEventListener() Silly Mistake To Avoid
Fahim Zada
Fahim Zada

Posted on

JavaScript addEventListener() Silly Mistake To Avoid

Hi there,
Using addEventListener() for handling the event is a better way. You can define the function separately, which you want to execute upon the event that occurred on your desired element.

Now you have the freedom to use that function for other elements of events, ensuring the reusability. However, some beginners tend to make a mistake by invoking it directly and passing it to addEventListener(). Here is an example explaining different ways and scenarios.

const btn = document.querySelector(".btn")

//This way, if these statements are required only for this 
//Particular element event
btn.addEventListener("click", () => {
  console.log("I'm clicked")
})

//Reusable function
const reusable = () => {
  console.log("I'm reusable function for events")
} 

//Here comes the mistake, You called it directly
btn.addEventListener("click", reusable())
//"I'm reusable function for events."
//Function executed without an event occurring
//Nothing will happen on click event

//Multiple Ways to fix it

//Don't call it directly
btn.addEventListener("click", reusable)

//Returning it inside another function
btn.addEventListener("click", ()=>reusable())

//Using bind function
btn.addEventListener("click", reusable.bind(null))
Enter fullscreen mode Exit fullscreen mode

Thanks for reading.

Top comments (0)