views:

1832

answers:

2

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?

+3  A: 

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...]

eimaj
Isn't this the sort of thing jQuery should be abstracting? I'm really surprised at this.
cletus
I remember trying e.target a while back running into problems with it. It looks like they've since been fixed (or else I've been fixed since a while back). Also, fancy termination tricks read like two lines to me ;)
Alan Storm
+8  A: 

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

Russ Cam