Event delegation.What is event delegation and why do we need it?…First of all a small recap on event handlers.  If we want to add an onclick event handler for all paragraphs in a document, this is the instruction in jQuery:

  1. $('p').click(function(){/* Code here */})

By doing this we add an anonymous function as a handler for the onclick event.

Before explaining event delegation you must know that as of version 1.4.1 jQuery has support for event delegation with the function live().

Event delegation makes use of two overlooked features of JavaScript events:event bubbling  and the action target. When an event is triggered on an element, for example a mouse click on a button, the same event is also triggered on all of that element’s parents.The event target hold’s the originating element (the button in our example).

So now let me tell you why event delegation is important and how it can help us.Let’s say we what to show an alert when someone click’s on the paragraphs in a section of our page, but that section of the page is altered often through Ajax. To be able to cache the onclick event for the paragraph event after the content is changed we use event delegation.

Ex (DOM):

  1. <div id="1">TEST</div>

Lets say that the content from the div with the id=1 changes though Ajax,but we want all paragraph from that div to have a function attached as a handler.What should be done is attach a click event to the div with the id=1 and then check the event target to see if it is a paragraph, so the click event is not attached to every paragraph in that section but to the section wrapper and then the event handler is checked. Code example:

  1. $(document).ready(function(){
  2. $('#1').click(function(event){
  3. if ($(event.target).is('p')){
  4. alert('Found');
  5. }
  6. });
  7. });

So that is event delegation.