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:
- use this that gives access back to the context element during the event.
- return false to cancel the event
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:
- an onload attribute will give you back the window
- an onclick attribute will give you back the HTML element
Example:
- Log the text of the button in the console:
<button class="btn btn-info" onclick="console.log(this.textContent)" >Click me to show this text in the console</button>
- this value is scoped demonstration
<body onload="alert(this)" onclick="alter(this)">
leads to:
- [object Window] when the document is loaded,
- [object HTMLBodyElement] whenever the user clicks something in the page.
preventDefault
If the return value is false, the event is canceled.
Example:
- By default, a anchor would navigate to the URL specified in the href element but we can prevent it by returning false
<a href="https://datacadamia.com" onclick="console.log(`Navigation to ${this.href} cancelled`); return false;">Click me</a>
- If you click on the link below, you would not navigate away but see the message instead
There are two exceptions, for historical reasons:
- The onerror handlers on global objects, where returning true cancels the event.
- The onbeforeunload handler, where returning any non-null and non-undefined value will cancel the event.
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:
- this that gives access back to the element
- and the Window.event (or for short event as Window is the global scope in the browser)
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>
-->