Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

553
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda