Web Development Tip of the Day (jQuery) – Delegation in On

jQuery logo

A few versions back jQuery got rid of the .live event handler. That handler was the way that you would handle events on elements being dynamically added to the page after the ready() event had fired. So with it gone you now use the .on handler, but it has one problem. It doesn’t work on elements that are dynamically added to the page. But you can make it work by using delegation, you attach it to an element that is there when ready fires, and use delegation filters to hit the one you are dynamically adding.



Note: Using document.body will give a slight hit on performance, much better to simply use a direct parent of the dynamic element, but make sure it is an element that is in the DOM when the page ready event fires.

Like the code you see here? You can hire me at Codeable.io - a WordPress specialist outsourcing site that vets developers to make sure they are of the highest standard. See all developers you can hire through Codeable here.

Posted in Code Snippets, Help Topics.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.