Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading