Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

window.onload = init

functioninit() {
    var button = document.getElementById("addButton");
    button.onclick = function(){ alert("Button has been pressed") };
}
<buttonid="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.

Solution 2:

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

Solution 3:

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

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

Post a Comment for "Timing Of Button.onclick Execution"