TIL: Passing parameters to callback functions

Today I tried to move an Event Listener callback function to it’s own module. It seemed simple enough. Take the following code example:


element.addEventlistener("submit", (event) => {

Now, my callback was a little more complex so it made sense to move to a module. The question then became why it didn’t work when I tried the following:


element.addEventListener("submit", eventHandler(event));


function eventHandler(event) {

I would get an error from app.js saying that event is not defined. After a little research I discovered on the MDN guide for addEventListener that you need to pass parameters using an anonymous function. My eventHandler() was fine – the issue was in the way I passed the parameter to the function in the callback. To fix it this was the solution:


// Arrow function syntax
element.addEventListener("submit", (event) => {

// Full function syntax
element.addEventListener("submit", function(event) {

Edit: turns out there is an even simpler approach when you’re only sending a single parameter – just don’t add the parameter to the callback function at all. This is also valid and you will still be able to access the parameter in the callback:

element.addEventListener("submit", eventHandler);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: