not adding ()'s to function calls?


#1

I have a different book saying this will work

window.onload = init;
function init() {
   var button = document.getElementById("addButton");
  button.onclick = handleButtonclick;
}

function handleButtonclick() {
 alert ("Button was clicked!");
}

note notice that when the functions are called (at the top), there are no ()'s . You would expect this code to NOT run properly and yet (1) it DOES; (2) adding the ()'s TO the function calls do NOT work? I just came from K’s chapter on Functions --> A Simple Functions as a sanity check, and sure enough “you function needs to be called…” sayHello(); <–

Thoughts appreciated. Thank yoU!!


#2

You don’t want to call handleButtonclick() here. This is the init step, when things are getting initialized. You want handleButtonclick() called when the button is clicked. To do this, you need to give the function - without calling it - over to the button so that when its clicked, it can call your function for you. This is why you’re not using () here. You just supply the function, by means of assigning to an onclick property, and when the button is clicked, it will internally take that function and call it for you, basically doing a button.onclick(event) where event is an automatically created object to describe the click event that occurred.