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?
Change
to
(Without the
().)Your original line,
button.onclick = handleButtonClick();calls thehandleButtonClickfunction and then assigns its return value tobutton.onclick. It’s exactly like…which calls
fooand then assigns its return value toa.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()).