Explain Codes LogoExplain Codes Logo

Jquery click event not working after append method

javascript
event-delegation
jquery
best-practices
Nikita BarsukovbyNikita Barsukov·Nov 25, 2024
TLDR

To handle clicks on dynamically created elements in jQuery, the best approach is to use event delegation.

$('#parent').on('click', '.new-child', function() { // Your best code goes here });

Here #parent is your static element that exists when the page loads, and .new-child is the selector for your freshly baked elements.

Explanation of event delegation

Event delegation caters to elements added after the initial page load. Direct event bindings are only applied to elements present at the time of the bind, leaving newly appended elements high and dry. Event delegation allows us to bypass this by binding the event to a parent element that exists at the time of page load. The .on() method binds the event to the static parent with a selector for descendants to trigger corresponding events.

Best practices for event delegation

Selection of a static parent

It's best to bind events to a close static parent for better performance.

$('#container').on('click', '.btn-add', function() { // Because every good container needs a button, right? });

jQuery version

To use .on(), your jQuery version must be 1.7 or above. For prior versions, you can use .delegate(), but .on() is recommended for improved performance.

Understanding event flow

Understanding the fundamentals of event bubbling is key, as it allows events to be trapped by parent elements even if they are bolted on post-binding.

Avoiding Miss-steps

  • Don’t delegate to dynamic elements. Always delegate to a static parent that's around during page load.
  • Make sure the selector string provided to the .on() shove matches your future elements.
  • Avoid using body or document as the parent for delegation. This can hurt performance if your page becomes an event goldmine.

Real-world scenarios and solutions

Scenario 1: An unresponsive dynamically loaded form

Have a dynamically loaded form with a disobedient submit button? Use a static element as a parent for your delegate:

$('#form-container').on('click', '#form-submit', function() { // "I solemnly swear I am up to no good" - Form submission logic });

Scenario 2: Handling events on infinite scroll content

When your content loads with infinite scroll, don't fret! Delegate the event to the container:

$('#scrolling-container').on('click', '.newly-loaded-item', function() { // New item, who dis? - Event handling for each item });

Scenario 3: Click events on a dynamically generated list of items

If you generate a list dynamically, delegate from the list's container:

$('#list-container').on('click', '.list-item', function() { // I bet you clicked this expecting something more interesting! });

Pearls of wisdom

Performance tuning

For complex applications, performance plays a crucial role. Few tips:

  • Limit the scope of delegated events. Opt for a container close to the dynamic elements rather than something global.
  • Minimize the number of delegated events. Excessive delegation can lead to performance bottlenecks because every event bubbles up to the static parent.

Use of .off() with .on()

Prevent unintended behavior by unbinding old events using .off().

$('#parent').off('click').on('click', '.child', function() { // Rinse and repeat });

Technique for older jQuery versions

For those stuck in the past, .delegate() is your friend.

$('#parent').delegate('.child', 'click', function() { // Practicing safe clicks });

Debugging event delegation

  • Verify your selector with .on() matches your new elements.
  • Use console.log inside the click handler to make sure it's working.
  • Ensure there are no JavaScript errors putting the brakes on event propagation.