Bind custom event handler after ajax load

In particular, I want to bind a lightbox to a specific element. Usually I just did this: $('a.lightbox').lightBox(); but this does not work, as I am doing some loading using AJAX. Looking at the jQuery API, I found .bind() and .live() , but after calling AJAX .load() I get nothing when I do $('a.lightbox').bind('lightBox') .

What am I missing?

+4
source share
2 answers

You need to add a callback function that handles this.

 $("#div").load(url, {}, function(){ $('a.lightbox').lightBox(); }); 

Binding will not help you, as the event does not fire the event.

+5
source

Another way would be to bind the element above in dom and check the type of target. For instance:

 $('#div').bind('click', function (event) { target = $(event.target); if (target.hasClass('lightbox')) { // do stuff here } }); 

Just don’t go too far, otherwise you will be too many clicks.

+1
source

All Articles