-1

I am wondering why doStuff() is called without clicking.

function pageReady() {
  var buttonBox = document.getElementById("buttonBox");
  buttonBox.onclick = doStuff();

  function doStuff() {
    buttonBox.style.background = "orange";
    buttonBox.style.width = "600px";
    buttonBox.innerHTML = "<h2>SURPRISE!!</h2>";
  }

}
  • 4
    `doStuff()` _calls_ the function and sets `onclick` to its _return value_ (`undefined`). You want `buttonBox.onclick = doStuff;`. – gen_Eric Oct 22 '21 at 20:27

1 Answers1

1

You're invoking the function, you should change

buttonBox.onclick = doStuff()

to

buttonBox.onclick = doStuff;

Now you're passing the function to the handler without invoking it.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
coderz
  • 72
  • 6