Question

I know that a div will appear at some point in my page's future DOM, and I know the id of it (it's generated by SharePoint javascript) - is it possible for me to use jQuery delegate to attach an event handler to this div prior to it existing in the DOM?

Also, how does this compare to .live() for this particular scenario?

Was it helpful?

Solution

Short answer: Yes

Long answer: As of jQuery 1.7+ .on() is prefered before the two you have mentioned, they are deprecated. This is an example on .on():

    $('#parent').on("click", "span.children", function() {
        if ( confirm("Are you sure?") ) {
            console.log(this);
        }
    }); 

OTHER TIPS

Yes, you could do this, but you could use .on method instead, and don't use .live, it is deprecated.

$(elements).delegate(selector, events, data, handler);  // jQuery 1.4.3+
$(elements).on(events, selector, data, handler);        // jQuery 1.7+

Yes, you can, but both methods have been superseded in favour of on() on recent versions of jQuery.

Also, live() always attaches the event handler to the (top of the) document, whilst delegate() allows you to choose where to attach the events, thus it can be more efficient if you know before hand where the element is going to be.

You should use .on(). And you should never use .live().

For a performance test between the three see: http://jsperf.com/jquery-live-vs-delegate-vs-on

Besides the fact that .live() is deprecated it is also very slow compared to the other two.

Basically what you are doing with .on() or .delegate() is add eventhandlers to elements within a container whether the elements already exist or if it is added to the DOM dynamically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top