How to get the onclick calling object?
To access the clicked element directly, use this
within an onclick
attribute:
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:
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:
- Leave the HTML alone, deal with events in the script.
- Use
addEventListener
or$.on()
. - 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.
That extra mile with handlers
Want to pass additional parameters to your event handlers? Use anonymous functions or bind()
:
Was this article helpful?