Table of Contents

Event - HTML On Attributes (known also as event handler content attributes)

About

This page is about HTML attribute that starts with on…

They are the second way to define an event handler. The frist way being to use the the on property of the Javascript element object known as the IDL handler (or event handler IDL attribute).

That's why this on HTML attribute are known as event handler content attributes

The name of the content attribute is the same as the name of the event handler.

Example

A onclick event handler

<button class="btn btn-info" onclick="console.log('Bouh!')" >Click Me</button>

Value

The handler value (ie code) sets in the on attribute must contain the body of javascript function.

The function body can:

In the specification, it's known as the internal raw uncompiled handler

Example

this

A inline event handler can use the inline variable this that gives access back to the element scoped by the type of event:

Example:

<button class="btn btn-info" onclick="console.log(this.textContent)" >Click me to show this text in the console</button>
<body onload="alert(this)" onclick="alter(this)">

leads to:

preventDefault

If the return value is false, the event is canceled.

Example:

<a href="https://datacadamia.com" onclick="console.log(`Navigation to ${this.href} cancelled`); return false;">Click me</a>

There are two exceptions, for historical reasons:

function (event, this)

This example is using the Window.event variable but it's deprecated Windows.event web api

A body event handler that calls a function with:

let handleClick = (event, element)=>{
   console.log('The event has:');
   console.log('  * the prototype: '+event.__proto__.toString());
   console.log('  * the type: '+event.type);
   console.log('  * been triggered by: '+event.srcElement.localName);
   console.log('The element clicked has:');
   console.log('  * the text: '+element.textContent);
   console.log('  * with the class '+element.className);
};
<button class="btn btn-info" onclick="handleClick(event, this)" >Click Me</button>
<!--
Same as
<button class="btn btn-info" onclick="handleClick(window.event, this)" >Click Me</button>
-->

Documentation / Reference