Why Do Inline Event Functions Use Quotations and Parentheses, While Event Handler Properties Only Require the Function Name?
Handler attributes make it easy to include behaviors in HTML tags. You need to put the handler function in quotations and parenthesis like this
<button onclick="someFunc()"> ... </button>
However, with event handler properties, you simply assign the function name directly, without quotes or parentheses:
element.onclick = someFunc;
Why does calling a function during events have a different syntax for both of them?
Inline Event Attributes
When you use an inline event attribute, you specify the code to execute directly, without the need for an explicit handler function. The provided code is essentially the body of an automatically generated handler function.
For example, when you inspect the onclick
property of the button
element, you'll see a wrapper function automatically created around the specified code
<button onclick="alert('hi')">...</button> document.querySelector('button').onclick; // ƒ onclick(event) { // alert('hi') // }
This wrapper function is created internally by the DOM API, and it expects an event parameter. If you don't need the event parameter in your code, you can omit it, but the automatic function still receives it.
<!-- No event passed --> <button onclick="someFunc()">...</button> <!-- Event passed through --> <button onclick="someFunc(event)">...</button>
Event Handler Properties
On the other hand, event handler properties, such as element.onclick
, allows you to set a function directly without the automatic creation of a wrapper function. When you assign a function to an event handler property, it receives the event parameter directly.
const element = document.querySelector("button"); element.onclick = someFunc; // Will receive the event directly
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.