HTML attribute for event handlers seems like magic. In this article, we will understand their semantics
Suppose we have the following HTML snippet:
<button onclick='console.log(this);console.log(event);'>ClickMe</button>
When we click on the button we get
<button onclick="console.log(this);console.log(event);">
click { target: button, buttons: 0, clientX: 44, clientY: 20, layerX: 44, layerY: 20 }
this is the element where the onclick was added and the event is the click event raised when the button was click. From where those variables come ?
Let's see how HTML attribute for event handlers are working under the hood
When you use HTML attribute for the event (For example: onclick), The browser create a function under the hood which assigned as the handler of the relevant event ( For example: onclick).
This function has the following properties:
event parameterthis is bound to the element on which the handler is registeredThe following function mimics how the browser can generate the semantics of function:
function addHandler(elem,attrEvent) {
code = elem.getAttribute(attrEvent);
if ( code == null ) {
return
}
handler = null
try {
eval(`inner = function (event) { ${code}; }` )
handler = function(event) {
return inner.call(elem,event);
};
} catch(ee) {
console.log(ee);
}
elem[attrEvent] = handler
}
Whenever onclick atribute is changed, the addEvent will be called with the relevant element and 'onclick'.
Whenever onclick attribute is changed in HTMLElement elem
addEvent( elem, 'onclick' )