How to provide arguments in event handlers

Darren Jones
February 23, 2022

When an event fires, the even object is implicitly provided to the event handler. This contains a number of properties that relate to the event. For example, the following event handler will log the number of milliseconds since the page loaded when the button is clicked:

copy code
javascript
button.addEventListener(‘click,handler)
const handler = event => console.log(event.timeStamp)

Notice that the event object doesn’t have to be provided as an argument to the handler function in the event listener. This is because it is provided as an argument implicitly, which is convenient, but also causes problems if you want to provide additional arguments to the handler function besides the event object.

This can be overcome using partial application. This involves defining a function that accepts any additional arguments and then returns another function that accepts the event object. For example, say you wanted to pass a message to the handler function, this could be done with the following code:

copy code
javascript
const handler = message => event => console.log(`${event.target} says ${message}`)

Notice the double-arrow structure that shows a function returning another function. message is the parameter of the first function and this then returns the second function that will implicitly accept the event object and also form a closure over the message parameter. This means that it will still be able to access the value of the message argument.

This is what it would look like using function declarations:

copy code
javascript
function handler(message){
  return function(event){
    console.log(`${event.target} says ${message}`)
  }
}

To use this, you need to provide the message as an argument in the event listener:

copy code
javascript
button.addEventListener(‘click,handler(‘hello’))

Know a better answer? Join our our community and let us know.