0

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);
}

1 Answer 1

3

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++) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.