1

The function tablePush pushes an id to the table upon a click on an item.
However, it runs without a click and I don't understand why.

Here is my code:

function tablePush() {
    console.log('OK');
    if (pickPicture) {
        console.log('TRUE');
    } else {
        console.log('on rentre dans le else');
        console.log(this);
        var idPic = this.getAttribute('id');
        console.log(idPic);
        table.push(idPic);
        pickPicture = true;
    }
}

var picture = document.getElementsByClassName('picture'),
    table = [],
    pickPicture = false;

for (var i = 0; i < picture.length; i++){
    picture[i].addEventListener('click', tablePush());
}
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33
Sifey
  • 29
  • 4
  • @Quentin — Better dupe target: [addEventListener in Javascript triggers the click event automatically](https://stackoverflow.com/q/11489734/4642212). – Sebastian Simon Aug 30 '18 at 09:22

3 Answers3

5

The line:

picture[i].addEventListener('click', tablePush());
                                              ^^

does not add the function tablePush, but the result of the invocation of tablePush(). This is so, because the parens () at the end mean "invoke this function now". To correct your code, use:

picture[i].addEventListener('click', tablePush);
                                              ^ no parens
pid
  • 11,472
  • 6
  • 34
  • 63
3

You are calling the function while adding event listener.

You need to update from

picture[i].addEventListener('click', tablePush());

to

picture[i].addEventListener('click', tablePush);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
2

You are calling it.
You need to register the function tablePush (instead of invoking it):

picture[i].addEventListener('click', tablePush);
Maor Refaeli
  • 2,417
  • 2
  • 19
  • 33