0

Let us say we are adding several elements to the dom. What is the best way to make sure these elements also have a click handler added to them? For example, if I have a click handler on all elements with the class "canvas-section", and I keep adding "canvas-section" elements, what is the best way to make sure in Jquery that these new "canvas-section" elements also have that click handler added.

Before I used to use the "live" jquery function or "on" but those don't seem to work for elements that are dynamically added or added after the original click listener is added.

Chris Hansen
  • 7,813
  • 15
  • 81
  • 165
  • There is no "best" way. You can either do a direct binding on them, or make a delegate event handler on the parent of the dynamic children. Either way works. Asking for the "best" way is looking for an opinionated answer. – Taplar Aug 30 '18 at 17:10

1 Answers1

1

You can bind the click handler to a parent object, including document, like this:

$(document).on('click', '.div-to-click', function() {
    console.log('hi!');
});

See: https://api.jquery.com/on/

nnyby
  • 4,748
  • 10
  • 49
  • 105