Event Handler - on Attribute (Content handler)

About

This page is about the definition of event handler via the HTML attribute that starts with on…

The handler value (ie code) is set in the value of the attribute.

You can also set the code via Javascript and the on property known as the IDL handler.

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>

Syntax

Event handler content attributes, when specified, must contain valid JavaScript code which, when parsed, would match the FunctionBody production after automatic semicolon insertion. ???

Variable

A inline event handler can use the inline variable

  • this - that gives access back to the element
  • event - gives access to the event

this

A inline event handler can use the inline variable this that gives access back to the element

Example that will 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>

event

A inline event handler can have as argument:

  • this that gives access back to the element
  • and the event
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>

Powered by ComboStrap