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

3 Answers 3

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

Comments

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

Comments

2

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.