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

218
Vistas
Basic JS Question, Arrow Function with a callback using parameters in addEventListener

I have a basic function here. I want to be able to pass parameters into it. However, it is being called by the addEventListener. Now, after reading on here and researching I got it to work so that if I put the TOP option in - it works. When I use the bottom option, just below it -it does not work. (Not if I want to use parameters). I just am wondering a basic explanation as to why the arrow function with a callback can take parameters, how is this going round exactly? Not sure I am explaining my question well.

for (i = 0; i < dots.length; i++) {
  dots[i].addEventListener('click', (e) => imgChoose(e, i));
}

for (i = 0; i < dots.length; i++) {
  dots[i].addEventListener('click', imgChoose);
}

var i = 0;

function imgChoose(e, i) {
  var test = dots[i].className;
  console.log(e);
}
about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

It's got nothing to do with arrow functions specifically, you can use normal functions too. What matters is that when addEventListener calls your function, it will pass in exactly one parameter: the event. If you want to then call a function with two parameters you can, but you must write that code yourself.

Here's how it would look with a regular function:

dots[i].addEventListener('click', function (e) { imgChoose(e, i) });

P.S.: as written, you have a single variable i which is being used for all the click callbacks. So they're all going to use the final value of i, which will be equal to dots.length. You should create i in the initialization of your loop, and make sure to use let, not var.

for (let i = 0; i < dots.length; i++) {
about 4 years ago · Santiago Gelvez 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