Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the root element that a delegated event is bound to - jQuery

Tags:

jquery

Taking the following code:

    // Bind the click event to the thumbnails.
    $("ul.hpList").on("click", "a.hpThumb", function (event) {

        event.preventDefault();

        var $this = $(this),

        // Surely there has to be a smarter way to do this.
            $hpList = $this.parents("ul.hpList");

        changeItem($this, $hpList);

    });

How do I better identify the root ancestor element that the event is bound to. I feel awful searching the DOM for this.

like image 660
James South Avatar asked Nov 23 '11 15:11

James South


People also ask

What is the delegate () method in jquery?

The delegate() method attaches one or more event handlers for specified elements that are children of selected elements, and specifies a function to run when the events occur. Event handlers attached using the delegate() method will work for both current and FUTURE elements (like a new element created by a script).

What is event delegation jquery?

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.


2 Answers

Since jQuery 1.7, the delegateTarget property is included in the event object given to you as the first parameter, which (according to the docs), gives you:

The element where the currently-called jQuery event handler was attached.

So give the following a go;

$("ul.hpList").on("click", "a.hpThumb", function (event) {
    event.preventDefault();

    var $this = $(this),
    var $hpList = $(event.delegateTarget);

    changeItem($this, $hpList);
});
like image 64
Matt Avatar answered Oct 14 '22 11:10

Matt


It's not clear to me what you're actually trying to find, but:

Use event.target inside your handler to determine which actual DOM element triggered the event.

Use $(this) to determine which DOM element the handler is attached to, which may be the same thing or may be a parent of the event target.

Use .closest() to find an element's closest ancestor which fits a given selector.

like image 31
Blazemonger Avatar answered Oct 14 '22 10:10

Blazemonger