Explain Codes LogoExplain Codes Logo

Jquery .live() vs .on() method for adding a click event after loading dynamic html

javascript
event-delegation
performance-optimization
best-practices
Alex KataevbyAlex Kataev·Aug 28, 2024
TLDR

Substitute .on() when attaching click events to dynamic content. .live() is outdated. If you need to respond to clicks on a present or future element with the class .dynamic-btn, apply:

$(document).on('click', '.dynamic-btn', function() { // Karma loves action here. });

This ensures that click events are fired on elements that appear even after this code is run.

Switching from live to on

The .live() method has been deprecated and replaced by the .on() method. For handling events on dynamically added elements, .on() is the correct method.

Dining with event delegation in on()

A fancy house party where everyone attending must shake hands with the host is an analogy. That's event delegation for you, using the .on() method.

It's an efficient way to dynamically assign events, where you attach a single event handler to a parent element. Using .on(), we bind the event to the parent (the host) and it's served to every matching child (guests), whether they have just arrived (dynamically appended) or were already present.

// Here's our chatty, sociable host, welcoming guests with a warm handshake: $('#parent-element').on('click', '.dynamic-item', function() { // Handle the click like a firm handshake. });

Avoid using $(document) as a default event handler. Delegation to the nearest parent elements gives a higher degree of encapsulation and performance.

In transition: polyfill for live()

Not ready to abandon .live() due to a long-term committed relationship? It's alright; you have a polyfill to help you make the transition smooth while maintaining an old application.

if (typeof jQuery.fn.live === 'undefined') { jQuery.fn.live = function(events, data, callback) { // Injecting 'on' steroids into 'live': jQuery(this.context).on(events, this.selector, data, callback); }; }

This polyfill provides a safety net, ensuring that code using .live() won't break during the transition process.

Crushing on performance with on()

Some strategies to ensure optimal performance using .on():

  • Try to bind the event handler to the closest static parent elements.
  • Always check whether elements exist prior to binding events.
  • Assign an accurate filter in the form of a child selector in .on() method to isolate and target dynamic elements effectively.

Preventing common pitfalls with on()

Here are some potential hurdles and solutions with .on()***:

  • Remember to control the event propagation flow. Do not stop it unexpectedly with event.stopPropagation().
  • Selector accuracy: Always ensure that your selectors accurately target the intended elements.
  • Dynamic parent elements: Keep in mind that if the event handler's parent element is dynamically replaced, the binding may break. Always guarantee your parent object is a permanent resident in the DOM.