Event Handlers

Suppose we want to execute the following unnamed function when the user presses an HTML button element.

var doSomething = function () {
    ...
};

To make this happen we have to register the function as a function handler for the click event.  One way to register the function as a function hander for the click event is to set the onclick property when declaring the button in the HTML file.  Notice that the property name is onclick and that we include parenthesis after the name of the function.

<button id=”test-button” onclick=”doSomething()”>Press Me</button>

A newer strategy, known as unobtrusive JavaScript, requires us to include all JavaScript, including registering button handlers, in external JavaScript files.  With unobtrusive JavaScript we register the button handler for events using the addEventListener method.  The following JavaScript code is equivalent to the code above.

document.getElementById(‘test-button’).addEventListener(
    ‘click’,
    doSomething,
    false
);

In the above code,

  • ‘click’ is the name of the event,
  • doSomething is not a function name, but rather a variable that holds a reference to a function
  • false instructs the browser to fire the event in the bubbling phase.

If we don’t have a reference to a function, but rather a function definition we can register the function as an event handler by setting the onclick attribute, as shown below.

function doSomething() {
    ...
}

document.getElementById(‘test-button’).setAttribute(“onclick”, “doSomething()”);

The Event Object

When an event is triggered, information, such as the target element that caused the event and the event type, is stored in a global variable named event.

In DOM-compliant browsers, the event object is passed as an argument to the event handler.

var doSomething = function (event) {
    console.log(event.type);
    console.log(event.target.id);
};

Please see the Mozilla documentation for a complete list of the properties and methods in the Event object.

© 2018 – 2020, Eric. All rights reserved.