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

A bowler hat with radio waves behind it

From Layoff to Leadership: Tom Conlon’s Journey to a Prosperous Business

Welcome to Your 2024 Branding Pep Talk

A bowler hat with radio waves behind it

CEO Tom Conlon talks shop on Podcast Marketing Secrets