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) {

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 () {

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

Building a Static API with Node.js

Learn how to build a static API with Node.js. We'll write a node build script that converts local YAML files into a set of structured JSON output files.

Apr 09, 2020

Compile ES6 Code with Gulp and Babel, Part 4

In the fourth of five parts on compiling multiple ES6 files into a minified bundle, you will learn how to minify your bundle and automatically clean up temporary build files.

Dec 20, 2018

Don't Do Stupid Shit with JavaScript

The JavaScript community is large. Use it to make your code better.

Apr 20, 2020