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

181
Vistas
pass the event and the element to the handler via event listener

I want to attach keypress event listener to each of words dom elements and pass the element itself ( I mean word) to the eventHandler ok?

So I tried this but it seems that I lose the event itself:

const eventHandler = (e, word) => {
    console.log('keypressed', String.fromCharCode(e.which), word);
}

words.forEach((word) => {
    window.addEventListener("keypress", eventHandler.bind(event, word));
}); 

String.fromCharCode(e.which) should bring the pressed key on keyboard but it returns nothing!!

How can I fix this?

Edit:

Here is the simpler reproduction of the issue: press any key on the keyboard and see the event is undefined:

const eventHandler = (event, word) => {
    console.log('keypressed', event, word);
}
window.addEventListener("keypress", eventHandler.bind(this, event, 'word'));

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The event is implicitly passed, and will be the last parameter after all the bound parameters.

So you would use eventHandler.bind(null, word) and then the handler should be declared eventHandler(word, e) {...}

const button = document.getElementById('b');

function handler(bound_arg, event){
  console.log(event.target);
  console.log(bound_arg);
}

button.addEventListener('click', handler.bind(null,'bound'));
<button type='button' id='b'>Bound</button>

But this isn't very intuitive, and since bind() creates a new function anyway you could simply use an anonymous function to pass the word.

window.addEventListener("keypress", (e) => eventHandler(e, word));
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