Adding event listeners to dynamically added elements using jQuery

Wiz picture Wiz · Aug 22, 2012 · Viewed 126.7k times · Source

So right now, I understand that in order to attach an event listener to a dynamically added element, you have to redefine the listener after adding the element.

Is there any way to bypass this, so you don't have to execute a whole extra block of code?

Answer

Jack picture Jack · Aug 22, 2012

Using .on() you can define your function once, and it will execute for any dynamically added elements.

for example

$('#staticDiv').on('click', 'yourSelector', function() {
  //do something
});