Reputation: 55
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
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