Roger Bergante
Roger Bergante

Reputation: 55

Confusion with window.onload

I just copy pasted this bit from a book:

window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick();
}
function handleButtonClick() {
alert("Button has been clicked");
}

The problem is that the alert appears when I load the page, not when I click on the button. Does anybody why?

Upvotes: 1

Views: 1234

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075705

Change

button.onclick = handleButtonClick();

to

button.onclick = handleButtonClick;

(Without the ().)

Your original line, button.onclick = handleButtonClick(); calls the handleButtonClick function and then assigns its return value to button.onclick. It's exactly like

var a = foo();

...which calls foo and then assigns its return value to a.

You don't want to do that, you just want to assign the function reference to onclick. So you refer to the function by its name, without calling it (so, without the ()).

Upvotes: 5

Related Questions