Skip to Content Skip to Menu

Javascript Plugin not working on AJAX loaded content

This is a common little problem I've come across a few times, and the first time it happened it took damn long to find the answer. The main case that I come across this issue is when a have popup jQuery plugins such as thickbox or colorbox which load an image or content in a nice popup. These are generally called via using a class name attribute for example:

<a href="path/to/image" class="thickbox"><img src="thumbnail" alt="alt name" /></a>

This is the standard thickbox one above where a class of "thickbox" is used to call the plugin.

Now in relation to AJAX. Say I load some content via AJAX, and this content requires the use of an image popup via thickbox. Should you apply the class to an element you would think it works straight off the bat. Quite often this is not the case. Because AJAX content is not part of the orginal DOM, this content has not had the plugins applied to it. So you will need to re-initialise the jQuery/javascript plugin in order for it to work on the AJAX content. I will use thickbox as an example:

$(document).ready(function(){
//click event - for example
$('a.reload').click(function(){
//ajax content
$.post('ajax-loader.php', {id : $(this).attr('id')}, function(data){
tb_init('a.thickbox, input.thickbox'); //reload thickbox plugin
$('.ajax_content').html(data);
}
});
});

tb_init() is a function in the plugin that initialises thickbox on the elements with that selector. You may need to make your own, or find the function that does it in the plugin you're using. Good luck, hopefully I may have saved you some time.