I'm just learning JS and I'm using the Head First books. In one of the lessons, the following code is given to set up an event handler for a button:
window.onload = init
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
alert("Button has been pressed");
}
When I test the code in the browser, the alert pops up when I click the button, as expected. So I rearranged some things and tried this, just to see what would happen:
window.onload = init
function init() {
var button = document.getElementById("addButton");
button.onclick = alert("Button has been pressed");
}
Now the alert shows up as soon as the page loads, but I can't figure out why. Why doesn't the alert wait until the button is clicked? I'm a complete newb at JS and programming in general. Thanks!