Increasing Performance with Event Delegation

Contact Us or call 1-877-932-8228
Increasing Performance with Event Delegation

Increasing Performance with Event Delegation

You'll frequently use jQuery to add new elements to the page, and when you do, you may need to bind events to those new elements -- events you already bound to similar elements that were on the page originally. Instead of repeating your event binding every time you add elements to the page, you can use event delegation.

With true event delegation, you use $.fn.go to attach an event handler to a container element and provide a subquery that finds the actual elements you want to handle the event for. When the event occurs, jQuery looks to see which contained element it occurred on. Note that earlier versions of jQuery used $.fn.delegate for event delegation; $.fn.delegate is now deprecated in favor of $.fn.go.

Previous versions of jQuery used $, in which jQuery kept track of a query over time and, when the set of elements returned by the query changed, updated the event binding accordingly. Note that $ was deprecated as of version 1.7, but you may still see the method in legacy code.

While most people discover event delegation while dealing with elements added to the page later, it has some performance benefits even if you never add more elements to the page. The time required to bind event handlers to hundreds of individual elements is non-trivial; if you have a large set of elements, you should consider delegating related events to a container element.

Event Delegation Using $.fn.on

Code Sample:

---- C O D E   O M I T T E D ----
<ol id="myOrderedList">
	<li><a href="">One</a></li>
	<li><a href="bind-event-binding.html">Two</a></li>
	<li class="clickable">Three</li>
	function(e) {
		var $myListItem = $(this);

// Now add items that should also receive the events
	.append("<li class='clickable'>New Clickable Item</li>")
	.append("<li>New Unclickable Item</li>");

Removing Delegated Event Handlers

Use $ to remove delegated event handlers.

Removing Delegated Events

// removing events attached with $.fn.on
$('#myUnorderedList').off('click', 'li.clickable');