Function runs before 'click' event is fired

Hello! I need help with a piece of JavaScript code below:
-This code runs perfectly when executed (together with accompanying HTML and CSS files).

let aFigure = document.querySelectorAll('figure');

aFigure.forEach(element => {

 element.onclick = function(){

     element.style.width = '70%';

     element.style.height = 'auto';

 }

});

-These code blocks execute the function as soon as HTML is loaded, before the ‘click’ event, although both are of the same logic as the first.
1:

function boxAdjuster (box) {

    box.style.width = '70%';

    box.style.height = 'auto';

}

let aFigure = document.querySelectorAll('figure');

aFigure.forEach(element => { boxAdjuster(element) });

2:

function boxAdjuster (box) {

    box.style.width = '70%';

    box.style.height = 'auto';

}

let aFigure = document.querySelectorAll('figure');

aFigure.forEach(element => {

    element.addEventListener('click', boxAdjuster(element))

})

Please highlight/clarify the mistake in the code or code logic. Thanks!

Hi @leukeieonest02789004
all you code snippets do different things, they aren’t the same at all.
In the second code block, there’s no event involved.

You’re calling the function boxAdjuster on each element stored in the array aFigure as soon as the js is loaded.

In the third snippet, you have an event listener waiting for a click event. But you invoke the function immediately.
You have to write it as an anonymous function. Like this:

element.addEventListener('click', function() { boxAdjuster(element) });

Thanks, mirja_t!
I understood you in the third snippet. What if I rewrite the second snippet like…

aFigure.forEach(element => { element.onclick = boxAdjuster(element) });

Is it the same issue as the third snippet earlier?

Same thing: It will run immediately.
Take a look at your first snippet. You have an anonymous function there, too:

Alright. Thanks again. :slightly_smiling_face:

1 Like