Search code examples
jqueryevent-delegation

Get container with on() in jQuery


I have a button inside a div to hide that div and I want to pass the div to the handler. Here is my current code:

$('#hidden-div').on('click', '#hide-btn', { element : $('#hidden-div') }, hideElement);

Is there any way to avoid reselecting the container? Something like this would be nice:

$('#hidden-div').on('click', '#hide-btn', { element : $(this) }, hideElement);

Solution

  • event.delegateTarget holds a DOM element reference.

    $('#hidden-div').on('click', '#hide-btn', hideElement);
    
    function hideElement(e) {
        $(e.delegateTarget)//do stuff
    }
    

    You'd still have to wrap it inside a jQuery object, but creating jQuery objects from DOM element references does not query the DOM.