KB Article 10433

Contact Tech Support

 Email Tech Support
 (250) 655-1766
 [7:30 - 5:00 PST]
Your Meeting ID will be Provided by a Rep.
Tech Support
Tech Support Home
Software Updates
Knowledge Base Search
Recent KB Articles
Product FAQs
Code Samples
Tech Blog
System Requirements
Installation Instructions
Support Testimonials
Contact us to...
Create a Ticket
Request a Free Demo
Suggest a New Feature
Submit Feedback
Upload a Large File
Other Services
Software Training
Professional Services

Delegation for multi-element jQuery event handlers

Product: WebSmart ILE Type: Frequently Asked Question

When trying to attach an event to multiple elements, a common practice is to select all of the elements we want then attach an event handler to it.

jQuery("ul li").click( function() {
  // click event 

However, this will attach your event handler to every matched element and only those currently on the page. This creates a large memory foot print, and as new elements are added to the page, you will need to reattach the handler again. A good example of this is the jQuery Mobile List template, where memory and performance matter more and new content is created without reloading the page.

A better way to attach an event to multiple elements is to attach the event to the parent element of the elements you want to trigger on, then pass the descendent selector as its delegate.

jQuery("ul").on( "click", "li", function() {
  // click event 

With this, you're only attaching 1 event handler, to the "ul". Because we know the parent element will have the "click" event triggered as the event bubbles up the tree, this will work the same as attaching the event to each "li" element. When the event bubbles or propagates to the parent element, it triggers the selected "li" to handle the event. The two main benefits are:

  • Less memory foot print. You are technically only attaching one event handler to the "ul" element, and not to each "li".
  • This also applies to future "li" elements that don't exist yet. For as long as the same ul exists, any descendents will get triggered through the delegates. This is great for applications where content is loaded through AJAX calls.

You can read more information on why you should use delegates on jQuery's own Event Delegation page, and check out the details on how to delegate a handler with jQuery.on()

Rate This Article

Did this example help you to achieve your goal?
 Yes  No  Don't Know

Enter additional comments below.   If you want to hear back from us, include your contact information.

Email Address:
Please enable JavaScript in order to rate this page.