Best way to get the Original Target

36,421

Solution 1

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

Solution 2

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

Solution 3

Using event.originalTarget can cause "Permission denied to access property 'XYZ' from a non-chrome context" -error, so i'd recommend using following:

var target = event.target || event.srcElement || event.originalTarget;

event.target works on Firefox, Opera, Google Chrome and Safari.

Solution 4

In conjunction with How to detect a click outside an element? here is how you might trap a sub-widget with similar hide-when-clicked-outside functionality to prevent your own pop-over from hiding along with it; in this case, we are trapping the JQuery UI Datepicker pop-over widget:

// not using jquery .one handler for this, so we can persist outside click later
$('html').click(function(evt) {
    // just return if element has the datepicker as a parent
    if ($(evt.target).parents('#ui-datepicker-div').length>0) return;

    //toggle shut our widget pop-over
    $('#mywidget').toggle();

    // now, unbind this event since our widget is closed:
    $(this).unbind(evt);
});
Share:
36,421
Alan Storm
Author by

Alan Storm

Portland based Web Developer/Programmer/Engineer. Projects include No Frills Magento Layout, the only Magento layout book you'll ever need and Commerce Bug, the debugging extension for the Magento Ecommerce system. If you're interested in low cost, in-depth mentoring/tutoring, checkout my Patreon campaign.

Updated on July 03, 2020

Comments

  • Alan Storm
    Alan Storm almost 4 years

    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?