Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get the Original Target

What's a jQuery like and/or best practices way of getting the original target of an event in jQuery (or in browser javascript in general).

I've been using something like this

$('body').bind('click', function(e){         //depending on the browser, either srcElement or          //originalTarget will be populated with the first         //element that intercepted the click before it bubbled up         var originalElement = e.srcElement;         if(!originalElement){originalElement=e.originalTarget;}                          }); 

which works, but I'm not pleased with the two line feature sniffing. Is there a better way?

like image 589
Alan Storm Avatar asked Jan 27 '09 21:01

Alan Storm


People also ask

How do I get the ID of a clicked element?

One of the ways to get an ID attribute of a clicked element is that you actually attach click events to all the buttons inside For loop. Get DOM references to all the buttons by invoking getElementsByTagName() on the document object with an argument button.

What is the difference between event target and event currentTarget?

event. currentTarget tells us on which element the event was attached or the element whose eventListener triggered the event. event. target tells where the event started.

How do you get a class from event target?

To check if event. target has specific class, call the classList. contains() method on the target object, e.g. event.

How do I find my e Target ID?

To get the attribute of a target element in JavaScript you would simply use: e. target. getAttribute('id');


2 Answers

You can do it in one line with var originalElement = e.srcElement || e.originalTarget; but it ain't pretty JQuery-like ;-)

[Edit: But according to http://docs.jquery.com/Events/jQuery.Event#event.target event.target might do...]

like image 126
eimaj Avatar answered Sep 30 '22 21:09

eimaj


I believe e.target is what you require

$('body').bind('click', function(e){                 e.target // the original target                 e.target.id // the id of the original target                                                }); 

If you go to the jQuery in Action website and download the source code, take a look at

  • Chapter 4 - dom.2.propagation.html

which deals with event propagation with bubble and capture handlers

like image 30
Russ Cam Avatar answered Sep 30 '22 21:09

Russ Cam