JS Tip of the Day: Event Attributes also Define Callback Functions

Event Attributes also Define Callback Functions
Level: Beginner

When defining event handlers for HTML elements, you have a number of options, including adding event handlers in the HTML through attributes, assigning a callback function to an element reference, or using addEventListener.

If you use an HTML attribute, the text of that attribute becomes the code executed when that event fires. In the following example, clicking the button will log a message.

<!-- html -->
<button id="btn" onclick="console.log('You clicked me!')">
  Click me
<!-- click:
You clicked me!

The happens because onclick attribute code becomes the body of a function that gets automatically created for the element and assigned to its onclick property. This is done much in the same way that you would define an onclick callback in JavaScript yourself. You can see this function by looking at the onclick property for an HTML element that has been defined with an onclick attribute.

// JavaScript
let btn = document.getElementById('btn');
function onclick(event) {
console.log('You clicked me!')

If you set your own callback function to the onclick property, this will overwrite the function defined by the onclick attribute. In doing this, however, the attribute value will not update. This means what the attribute shows may not be representative of the actual behavior of the event.

btn.onclick = function () { // overwrite attribute-set callback
/* click:
onclick="console.log('You clicked me!')"

Setting the onclick attribute dynamically will again re-set the onclick property with a new function containing code from that attribute value.

btn.setAttribute('onclick', "console.log('Stop touching me!')"));
/* click:
Stop touching me!

Using both event attributes and callback properties will not allow you to have more than one event handler for the same event in any given HTML element since they both use the same callback. If you need multiple event handlers in this manner, you can use addEventListener.

More info: