Event Binding to Dynamically Created Elements in JQuery

By North Street, A Creative Studio

jQuery event binding is pretty simple. Usually you just do something like this:

$('.gallery-featured').bind('click', function(){
	$('.promo').slideDown();
});

…and it works great.

Unless ‘.gallery-featured’ is a dynamically created element. In that case, there’s a chance that the bind call will happen before the element exists, and silently fail.

The solution is pretty simple. You instead bind to document, and using the ‘.on’ function, and specify the element that will eventually added. So the above code would simply be:

$(document).on('click', '.gallery-featured', function(){
        $('.promo').slideDown();
});

Source:
http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements

About north street

We engineer the thoughtful transformation of great organizations. Our proven process helps us understand what your competitors are doing right — and wrong. Want to learn more? Let’s chat.

More Notes

Team Spotlight: Matt Potter, Web Designer

Postcards from Puerto Rico: North Street Retreat ’22

We’re Hiring: Marketing Coordinator