Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

550
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Just declare a parameter for the function. The syntax is the same for named functions as for anonymous function expressions.

document.querySelector('input').addEventListener('keyup', func);
function func(e /* event object */ ){
  console.log(e.keyCode);
}
Type something here: <input>

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report

0

You need not explicitly pass it

function func(e) {
  console.log(e.target.value)
}


document.getElementById('input').addEventListener('keyup', func)
<input id='input'>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!