Diety Dieticheskie-produkty Protsedury Sredstva Uprajneniya Fitnes Gimnastika Yoga Pitanie Tsellyulit Zdorove Krasota

Event Delegation and Event Bubbling are two important concepts in JavaScript. If you don’t know what Event Bubbling is please learn it here.

Event Delegation is a mechanism in which instead of adding event handlers to all elements in DOM tree we attach event listener to their parent and handle all events in one place. Event Delegation is really helpful in optimizing web pages. Let’s take a look at example to demonstrate where to use it and how to use it.

Imagine a web page with the above mentioned table. You want to give user the ability to select/de-select a row whenever he clicks on some row. If row is not selected then on clicking it becomes selected and if it is selected then on clicking it become un-selected. Following is the result that you want to achieve

To achieve this thing we will use jQuery and we all know that using jQuery this is quite easy effect to achieve. To achieve this you can use following code:-

 

  $(document).ready(function() {
    $("#user_info tr").click(function(event) {
       $(this).toggleClass("selected");
    });
  });

Now when we click on any row it toggles it’s selection and we have achieved the same effect that we want and that is shown in above picture, cool!.

But there is a catch. Imagine there are 10,000 rows and you want to achieve same effect. Remember that by using above code snippet you are attaching event to each individual row element in table and this means that when there are many rows in table our web page will start behaving slowly and that is not what we want.

This is where Event Delegation comes handy. Instead of attaching event to each row we will attach at one place and will attach event to parent (table) only. By Event Bubbling we know that whenever event occurs on one element that event gets bubbled up in DOM hierarchy and we will be going to take advantage of this.

Event Delegated version of our earlier code will look like this:-

 

  $(document).ready(function() {
    $("#user_info").click(function(event) {
       $(event.target).parent().toggleClass("selected");
    })
  });

Both code snippets in this post have same effect but second one is highly optimized as compared to first one because event handler is attached to only one element. Event object has a target property which indicates that on which element actually the event occurs and that property remains same in whole DOM hierarchy.

I hope you like this quick performance tip.

Tagged with:
 

Leave a Reply

Your email address will not be published. Required fields are marked *