Colorbox and Content returned via ajax

I am using jQuery colorbox for popup user accounts in a window. I also have a button that loads more users to the page via ajax, but for some reason users loaded with ajax do not appear in the colorbox window. How can I get colorbox to work with content that was returned via ajax?

function loadMore(pageNo) { //$("#loading").html('Loading...').show(); var url = '/search/resultsAjax'; $.get(url, {page: pageNo}, function(response) { $("#results").append(response); //$("#loading").hide(); }); } $(document).ready(function() { var currPage = 1; $("a.next").click(function() { loadMore(++currPage); }); $("a.usr").colorbox({width:"960px", height:"90%", iframe:true}); }); 
+3
source share
3 answers

When you bind colorbox to $(document).ready() as follows:

 $("a.usr").colorbox({width:"960px", height:"90%", iframe:true}); 

jQuery goes to search the page, takes everything that matches a.usr , binds the colorbox to these elements, and then forgets everything about a.usr . jQuery will not remember that you are interested in a.usr , so the new ones will not be colorbox'd.

A common solution of this kind is to use .live() or .delegate() , but they will not work here because there is no colorbox event.

However, you can easily link the colorbox manually. Try changing loadMore to something more:

 function loadMore(pageNo) { $.get('/search/resultsAjax', { page: pageNo }, function(response) { var $html = $(response); $html.find('a.usr').colorbox({ width: '960px', height: '90%', iframe: true }); $('#results').append($html); }; } 

You simply turn the response HTML into a jQuery object, find all a.usr things in it, bind the colorbox to them, and then paste the new HTML into the DOM, as usual.

+6
source

If you want it to work globally, no matter how the content is downloaded:

 $('body').on('click', 'a.usr', function() { $(this).colorbox({width:"960px", height:"90%", iframe:true}); }); 
+8
source

Use this:

 <a onclick='parent.$.colorbox({href:"schedule_delete.php?sid=<?php echo $schedule_row->schedule_id; ?>"}); return false;'>delete</a 
+3
source

All Articles