This question has already been answered:

Here is just a left example. Why is the function that should be performed on a click just like that?

button = document.getElementsByClassName("button")[0]; block = document.getElementsByClassName("block")[0]; button.onclick = test(); function test(){ block.style.height = "100px"; block.style.background = "red"; } 

Reported as a duplicate by members of Pavel Mayorov , andreymal , sanmai , insolor , iksuy Sep 22 '17 at 8:39 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

    1 answer 1

    Because you assign onclick not a function, but the result of its execution.

    It will be right:

     function test(){ block.style.height = "100px"; block.style.background = "red"; } button.onclick = test;//без скобок 

    or

     button.onclick = function(){ block.style.height = "100px"; block.style.background = "red"; }