user1017882
user1017882

Reputation:

Am I understanding the jQuery delegate function correctly?

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?

Upvotes: 2

Views: 70

Answers (4)

PeeHaa
PeeHaa

Reputation: 72682

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.

Upvotes: 1

sQVe
sQVe

Reputation: 2015

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);
        }
    }); 

Upvotes: 3

João Silva
João Silva

Reputation: 91329

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.

Upvotes: 1

xdazz
xdazz

Reputation: 160853

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+

Upvotes: 1

Related Questions