Explain Codes LogoExplain Codes Logo

How to get the onclick calling object?

javascript
event-handling
unobtrusive-javascript
event-delegation
Alex KataevbyAlex Kataev·Jan 15, 2025
TLDR

To access the clicked element directly, use this within an onclick attribute:

<button onclick="alert(this.tagName)">Click me</button>

Here, this points to the <button> when it's clicked, returning its tag name instantly.

Breaking down event.target and this

In the world of JavaScript event handling, **this** and **event.target** hold distinct places. **this** is the element bound with the event, whereas **event.target** is the triggering element. They are different if the event bubbles up from a child element.

Inline handlers vs. Unobtrusive event handlings: The Face-off

Inline coding tends to throw HTML and JavaScript into the same pot, making your code a maintenance nightmare. Advancements in JavaScript gave us unobtrusive JavaScript. Here, event listeners are bound within JavaScript code using addEventListener or attachEvent (IE's old buddy). The result? A neat partition between your structure and behavior.

The cross-browser compatibility challenge

Different browsers have unique gimmicks to handle events. To ensure cross-browser compatibility, implement this coding pattern:

element.onclick = function(e) { e = e || window.event; var target = e.target || e.srcElement; // Remember this: IE is like a grumpy old man. It insists on using window.event and srcElement. };

Here, our code shows love to IE by accommodating window.event and srcElement.

Memory leaks: The Silent Killers

Watch out for memory leaks. Especially if you're dealing with grumpy old browsers. Unbind those event listeners when not needed. Your memory resources will thank you.

Managing multiple onload functions

When juggling multiple event listeners on the load event, keep your code clutter-free. Handle multiple functions with addEventListener. Bonus: You keep the global scope clean, and your debugger doesn't pull a Houdini on you!

If you have jQuery, flaunt it

Dealing with events is a cakewalk with jQuery. Use the mighty .on() method for event binding; it doesn't shy away from aiding in DOM manipulation, either. Remember, with great power comes... great flexibility!

A blueprint for unobtrusive JavaScript

Here's your guide to implementing unobtrusive JavaScript:

  1. Leave the HTML alone, deal with events in the script.
  2. Use addEventListener or $.on().
  3. No JS code in your HTML. Clean house, clean code.

Your guide to eventful onclick adventures

Making your way with Event Delegation

Event delegation lets you attach a single listener to the parent — like a chameleon it adapts to clicks from all children. Your memory resources breathe a sigh of relief.

document.getElementById('container').addEventListener('click', function(e) { var clickedEl = e.target; if (clickedEl.tagName === 'BUTTON') { // In parent-child relationships, the one who listens, wins! } });

That extra mile with handlers

Want to pass additional parameters to your event handlers? Use anonymous functions or bind():

// Anonymous function button.onclick = function() { handler(arg1, arg2); // It's like saying: "I don't know my name but I know my job!" }; // Using bind (for the classy folks out there) button.onclick = handler.bind(null, arg1, arg2); // Dear bind, let's handle this together. Yours, arg1 and arg2.