How to pass the key variable to eventListener function defined elsewhere?

Normally when you add eventlisteners you’d do:

input.addEventListener('keyup', function(e){// get e.keyCode here});

But what if I defined a function somewhere else and just wanna pass the function as a variable? It’d look something like this:

input.addEventListener('keyup', func);

How do I pass in the e as an argument here (or any other arguments in general)? Thanks.

>Solution :

Use a named function which passes e. e is the Event Object all event handlers pass as default. An event handler is the function called when a registered event is triggered. An event is registered when it is the first parameter of an event listener:

.addEventListener('keyup', eventHandler)

OR a onevent property

.onkeyup = eventHandler;

OR a inline attribute (don’t use this one, it’s no good)

<input onkeyup='eventHandler(e)'>

In the example below, A is an anonymous function and B is the same as A but has a named function as event handler.

const inputA = document.querySelector('.A');
const inputB = document.querySelector('.B');

// Anonymous event handler
inputA.addEventListener('keyup', function(e){
  console.log(e.key);
});

// Named event handler
inputB.addEventListener('keyup', keyHandler);

function keyHandler(e) {
  console.log(e.key);
}
<label>A: <input class='A'></label><br>
<label>B: <input class='B'></label>

Leave a Reply