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

London Biedron Header

Team Spotlight: London Biedron, Client Development Specialist

Rebrand

How to Roll Out a Rebrand

12 Mood Boards to Inspire Your Rebrand