2

I am confused as to why I am getting the console logging from formating(). When the code seems to be putting action listeners on the buttons within my HTML. What I would expect here is the code to wait until the user clicked to run formating(). I'm sorry if this is poorly worded I'm new to coding and trying to teach myself.

ps. I understand that there are easier ways to do this via Jquery but I am trying to teach myself the hard way first lol.

let i = 0;
while (i < data.length && i <= 8)
{
     //some other code above
     selectionA(i);
     i++;
}

function selectionA(selected)
{
     var classname = document.getElementsByClassname("classname");
     classname[selected].addEventListener("click", formating(selected), false);
}

function formating(i)
{
     console.log("you clicked on : + i = " class"
}

Result:

you clicked on: 0 class
you clicked on: 1 class
you clicked on: 2 class
you clicked on: 3 class
you clicked on: 4 class
you clicked on: 5 class
you clicked on: 6 class
you clicked on: 7 class
you clicked on: 8 class

without any class being clicked on.

Thanks for any help or suggestions anyone has!

Matthew R
  • 23
  • 4
  • `ormating(selected)` *calls* the function immediately and assigns the *return value* as the event listener. Since you have no `return`, it's implicitly `undefined`. You need to supply a function handle - likely `function() { formating(selected) }` – VLAZ Nov 19 '19 at 22:42

2 Answers2

1

addEventListener needs to assign the function variable. In your code you are calling the function immediately using (). To fix it you can remove them.

classname[selected].addEventListener("click", formating, false);

To pass argument to your function you can either wrap it in an anonymous function and call it or use bind (source):

classname[selected].addEventListener('click', formating.bind(null, event, arg1, ... ));
Kalimah
  • 11,217
  • 11
  • 43
  • 80
  • Thank you for the explanation. I understand and will have to do some reaserch on .bind on the dom. Thanks so much! – Matthew R Nov 19 '19 at 23:02
0

The second argument of the addEventListener method is expected to be a function reference.

Instead of

formating(selected)

you can use an anonymous function reference, such as:

() => formating(selected)
Rounin
  • 27,134
  • 9
  • 83
  • 108
  • 1
    To piggy back on this: If you want to just pass the function name rather than an arrow function, addEventListener will automatically pass in the even object as your argument (i) when it invokes the function. – anna Nov 19 '19 at 22:48