Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

551
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda