Table of Contents

DOM - Event Handler (On Attribute or Property Code registration)

About

An event handler registers:

They are known as:

A event handler in the DOM is not the standard definition of a event handler (ie a function that handle an event) because:

Syntax

Event handlers can be define in the following ways.

On Attribute

You can register the code that will handle the event with:

Example:

<button class="btn btn-info" onclick="console.log('Ouch !');">Poke me</button>

More .. What are the HTML On Attributes ? (known also as event handler content attributes)

They are less recommended because they mix up HTML and JavaScript:

Javascript Property (Idl)

DOM Event Handler - On Properties with Javascript (Interface Definition Language - IDL )

Example:

document.querySelector('button').onclick = function() {
   console.log('Ouch !');
}
<button class="btn btn-info">Poke me</button>

Because this is a property, only one function can be defined. If more than one function should be triggered for instance for the click above, you should add another event listener

Jquery on

Jquery on is a wrapper that permits to register event handler.

<button id="my-name-is" class="btn btn-info" role="button">My Name is</button>
<p></p>
<div id="my-name" class="alert alert-info" hidden >
    Nico
</div>
var hiddenBox = $( "#my-name" );

$( "#my-name-is" ).on( "click", function( event ) {
    hiddenBox.show();
});

Properties

Name

An event handler has a name, which always starts with on and is followed by the type of the event for which it is intended. Ref

See the list in the event type page

Not all HTML element will respond to event handler. For example, only media elements will ever receive a volumechange event fired by the user agent.

Value

The value is the code that will run when the event occurs.

The value is:

Initially, the value is set to null. When a value is set, a listener is created.

Listener

The event listener registration / creation happens when the value is being set to a non-null value.

When setting a value, an event handler creates implicitly only one event listener. Setting multiple handler definition for the same pair of element and a event type will execute only the last definition.

Demo:

let button = document.querySelector('button')
button.onclick = function () { console.log("IDL handler"); }; 
button.setAttribute("onclick", "console.log('Attribute Handler')"); 
<button>Execute the handler by clicking</button>

List

See the list in the event type page

While event handlers apply to all HTML elements, they are not useful on all HTML elements.

For example, only media elements will ever receive a volumechange event fired by the user agent.

Documentation / Reference