Friday, March 1, 2013

Thickbox with Ajax Calls

Thickbox is a webpage UI dialog widget written in JavaScript on top of the jQuery library. It is a fantastic plugin, just include the JS file and give your elements the correct class and it will work instantly. For example:

<a class="thickbox" href="thickboxexample.php?height=600&width=600">Click to Show Thickbox button!</a>

Then, the plugin will attach its events to the elements on the page load event, if you look into the thickbox.js you will find

$(document).ready(function(){
tb_init('a.thickbox, area.thickbox, input.thickbox');
});

The problem

I have a page that have a set of buttons at the bottom and that are rendered depending on some set of conditions, so I refresh the displayed by an ajax call...

$.ajax({
url: "refreshDisplayButtons.php",
success: function(){
// Render the new set of buttons
}
});

But, when the new buttons are generated and they have the "thickbox" class, once you try to click them nothing happens!!! Clicking the new generated (rendered) buttons from the ajax call does not work at ALL!!

The reason

Simply, your new generated buttons doesn't have thickbox events attached to them. Because you only had the thickbox plugin initialized once at the beginning of the page load and that is why your newly rendered buttons aren't working when you try clicking them.

Conclusion

You need to reinitialize the thickbox plugin to get it reattached to your new rendered buttons.

$.ajax({
url: "refreshDisplayButtons.php",
complete: function(){
/* I prefer to do it in the complete callback so to make sure that the buttons are already got displayed */
tb_init('a.thickbox, area.thickbox, input.thickbox');
} success: function(){
// Render the new set of buttons
}
});

No comments:

Post a Comment