I am curious about how the content of the inline element attribute event works under the hood.
We start off with a simple function
function handler(e) {
console.log(e);
}
Use Case 1
If we would want to add this handler to our button we could do:
<button onclick="handler();">Click Me</button>
Which Logs on click: undefined
Fair enough, we called a function without passing arguments.
Use Case 2
If we now change the button to take the event
as an argument:
<button onclick="handler(event);">Click Me</button>
We log on click: MouseEvent{ ... }
Now we log the event, as we could have expected
Use Case 3
But what if we just specify the function name?
<button onclick="handler">Click Me</button>
Nothing happens!, I was hoping just giving a reference to a function, would do the trick. So when "onlick" would happen, the referred function would be called with the proper event argument.
Use Case 4
When we add the handler in javascript:
const btn = document.getElementById('btn');
btn.onclick = handler;
it works, capturing the event and logs the related event
object.
Concluding Question
Whatever text/content/statement that we pass to onclick=""
inline, does it basically run eval()
on it? And when we attach it in javascript (btn.onclick = ...
) it goes through the proper process to intercept the event and then call bounded handler function and passes the corresponding event object with it (e.g. MouseEvent
)?
Quick Note
To be clear, this is an informative question, to understand the fundamentals, disregarding if it's considered a bad or good practice. That's not being discussed at this point.