Adding an event handler to a button

JavaScript code

// This code is contained in the head element or an external file function displayHello() { alert("Hello"); } // We can not attach an event handler to a button until after // the button is created, so this should not run until // after the window is loaded. function init() { document.getElementById("HelloButton").onclick = displayHello; } // This code waits until the document is loaded to attach the // event handler to the button. // Note how the init function is used as an object and referred // to by using its name. window.onload = init;