How HTML attribute for event handlers are working under the hood

HTML attribute for event handlers seems like magic. In this article, we will understand their semantics

HTML attribute for event handlers sample

Suppose we have the following HTML snippet:

HTML event handler attribute
 <button onclick='console.log(this);console.log(event);'>ClickMe</button>

When we click on the button we get

HTML event handler attribute sample - console output
 <button onclick="console.log(this);console.log(event);">
 click { target: button, buttons: 0, clientX: 44, clientY: 20, layerX: 44, layerY: 20 }
We can see that 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

The semantics of HTML attribute for event handlers

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:

  • The function gets as a parameter the event parameter
  • this is bound to the element on which the handler is registered
  • The body of the function is the content of the attribute. Thus, the value of the attribute should be JavaScript code.
  • As the content is the body of function - you can use return statement. The return should return bool value which determines if the event is canceled.

The following function mimics how the browser can generate the semantics of function:

Generating handlers from HTML event handler attribute
 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'.

HTML event handler attribute - pseudo code
 Whenever onclick attribute is changed in HTMLElement elem
   addEvent( elem, 'onclick' )