What is the use of Delegate() Method in jQuery?

 Posted by Bharathi Cherukuri on 2/7/2012 | Category: jQuery Interview questions | Views: 4154 | Points: 40
Answer:

The delegate() method can be used in two ways.
1) If you have a parent element, and you want to attach an event to each one of its child elements, this delegate() method is used.
Ex:Un-ordered List
Instead of attaching an event to each <li> element, you can attach a single event to <ul> element.

Example:

$("ul").delegate("li", "click", function(){

$(this).hide();
});


2) When an element is not available on the current page, this method is used.
.live() method is also used for the same purpose but, delegate() method is a bit faster.

Example:

$("ul").delegate("li", "click", function(){

$(this).hide();
});


This will hide any list items that are not currently available on the page. They may be loaded via an Ajax request and then append to it.
Using .bind() or .click() methods, you would have to manually attach events to these new list items once they are added.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response