A Closer Look at jQuery’s delegate Method
jQuery has several ways to attach an event to an element, and sometimes which one to use is not so obvious. In this article I am going to be focusing on .delegate() and some of the benefits of using it.
There are two primary times when delegate comes in handy. The first scenario is when you have a parent element, and you want to attach an event to each one of it’s child elements. A great example of this is an un-ordered list. Instead of attaching an event to each <li> element, you can attach a single event to the <ul> element. Lets take a look at an example of this.
Here’s the HTML for an un-ordered list:
<ul> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Five</li> </ul>
Here’s our JavaScript:
$("ul").delegate("li", "click", function(){
$(this).hide();
});
In this example we are saving some resources by only attaching one event, instead of five. In a small application, this won’t matter match, but in a larger app where you have a lot of event listeners, this can be a great performance booster.
Another instance where delegate is beneficial, is when an element is not currently available on the page. You might be thinking this is what the .live() method is for, and you are correct, but actually delegate is preferred because it’s a little bit faster.
$("ul").delegate("li", "click", function(){
$(this).hide();
});
This will hide any list items that aren’t currently on the page. Maybe some you load via an ajax request and then append to the list. With the traditional .bind() or .click() methods, you would have to manually attach events to these new list items after they are added.
So, how does delegate work? Well, with a traditional bind method, the event bubbles up to it’s parent element and then to each ancestor, broadcasting that the event was triggered by a descendant element. With delegate the container element gets bound to the event type (ie: “click”) and the CSS selector (ie: “<li>”). If an event occurs with one of it’s child elements, it checks to see if it was the correct event type and the correct element. If both of these conditions are met, it executes the defined function.
So, the next time you are about to use .bind() or .live(), ask yourself if .delegate() is a better solution.



Create A Simple PHP Contact Form
its not working also what does it mean by action pl...
Create A Simple PHP Contact Form
Thanks is there an easy way to add more fields I'm...
Create A Simple PHP Contact Form
You just need to change your forms action to form contact...