In this post, I will share a simple tip of how you can improve jQuery performance by using Event Delegation to add event listeners to the parent element, and in turn, check for events on its children.
First let’s take an example where there are a bunch of ‘li’ elements inside an unordered list. We have to use jQuery to provide a click event and perform an action, when the user clicks on a li element.
For this example, we are converting the li into hyperlinks (not by appearance but by functionality)
The code shows a typical way of adding a click event to every ‘li’ element – there are three event listeners. However there’s a better way to do this using the jQuery delegate function and reducing the number of event listeners. Here’s how.
The same event listener will be applicable to all ‘li’ elements that are added dynamically, i.e. at run time.
See a Live Demo
Will you give this article a +1 ? Thanks in advance