Bretto
Bretto

Reputation: 23

Timing of button.onclick execution

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!

Upvotes: 2

Views: 243

Answers (3)

Hatjhie
Hatjhie

Reputation: 1365

It is expected. Javascript would run alert("Button has been pressed"); you might want to change it to button.onclick = function() {alert("Button has been pressed"); };

Useful reading about this:

Why do you need to invoke an anonymous function on the same line?

http://www.quirksmode.org/js/events_advanced.html

Upvotes: 1

AstroCB
AstroCB

Reputation: 12367

You need to enclose it in a function, or it will execute immediately:

window.onload = init

function init() {
    var button = document.getElementById("addButton");
    button.onclick = function(){ alert("Button has been pressed") };
}
<button id="addButton">Alert</button>

This occurs because you're trying to assign alert() to the onclick property of a button, which is not possible. JavaScript often fails "nicely," acting oddly rather than throwing errors in an attempt to prevent webpages from breaking entirely. When it sees the alert(), it executes immediately.

If you wrap it in a function, you can assign the function to the onclick property and it will work as expected.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

Yep, onclick takes a function - simply passing alert() will execute immediately. You need to do:

button.onclick = function() {
    alert("Button has been pressed");
}

Upvotes: 0

Related Questions