Home

Pass Argument to addEventListener

When using the native addEventListener function, you may often want to pass arguments to the callback function. Anonymous functions are here to help.

Consider the scenario where you have a shared function (example log function below) that you want to call after some event occurs, like a click on a particular button.

function log(text) {
console.log(text);
}

Calling Function with Arguments Fires Once

It may seem like this would solve the problem, but it doesn't:

const button = document.getElementById("my-btn");
button.addEventListener("click", log("Hello!"));

When you use log("Hello!") as an argument, it gets executed when the code is parsed, not when the addEventListener function is executed (when the button is clicked).

Using an Anonymous Function

Instead, you can define an anonymous function, and inside it call the log function.

const button = document.getElementById("my-btn");
button.addEventListener("click", function () {
log("Hello!");
});

This pattern is a result of the API for this particular method (addEventListener). But it's also a common pattern in JavaScript. See here for a broader example and deeper explanation.

Let's Connect

Keep Reading

WTF is Hoisting?

Sometimes JavaScript code appears to behave oddly. Hoisting is one of the reasons why. Here's an introduction to the concept, with references to more in-depth explorations.

Aug 07, 2020

5 Reasons I'm Excited about Astro

Astro is the new static site generator on the scene. This is why I'm so excited about it.

Aug 24, 2021

Converting FormData to JSON in JavaScript

FormData is a useful interface for collecting data from a form. But it can be tricky to convert to JSON.

Apr 28, 2021