This chapter describes the DOM Event Model. The Event interface itself is described, as well as the interfaces for event registration on nodes in the DOM, and event listeners, and several longer examples that show how the various event interfaces relate to one another.
There are 3 ways to register event handlers for a DOM element.
// Assuming myButton is a button element myButton.addEventListener('click', greet, false) function greet(event) { // print and have a look at the event object // always print arguments in case of overlooking any other arguments console.log('greet:', arguments); alert('hello world'); }
This is the method you should use in modern web pages.
<button onclick="alert('Hello world!')">
The JavaScript code in the attribute is passed the Event object via the event
parameter.
// Assuming myButton is a button element myButton.onclick = function(event){alert('Hello world')}
Event handlers may be attached to various objects (including DOM elements, document, the window
object, etc.). When an event occurs, an event object is created and passed sequentially to the event listeners.
The Event
interface is accessible from within the handler function, via the event object passed as the first argument. The following simple example shows how an event object is passed to the event handler function, and can be used from within one such function.
function print(evt) { // the evt parameter is automatically assigned the event object // take care of the differences between console.log & alert console.log('print:', evt) alert(evt) } // any function should have an appropriate name, that's what called semantic table_el.onclick = print