Wednesday, June 27, 2012

How to add jQuery Thickbox on Ajax Generated Pages

The jQuery thickbox plugin is fantastic. All you have to do is include the js file, and give the elements that require a jQuery thickbox, a class of thickbox. Like below;

<a class="thickbox" href="thickboxexample.php?height=600&width=600">jQuery Thickbox Example</a>

The thickbox plugin then automically!! attaches its events to those elements. For ease of use this is great, but it has its limitations, because the events are attached on page load.
What happens when you want to attach a thickbox to an element that is generated via an ajax call?
Well you’re gonna kick yourself! You simply need to re-call the the thickbox initialise function within your ajax call, just like the example below:
$.ajax({
    type:       "GET",
    url:        "/ajax-content.php",
    cache:      false,
    data:       "f=foo&b=bar",
    loading:    $('.loading').html(""),
    success:    function(html) {
                    $("#ajaxContent").html(html);
                    //re-attach thickbox
                    tb_init('a.thickbox, area.thickbox, input.thickbox');
                }
});
I am assuming that you already know how to make an ajax call using jQuery, so I won’t explain the above code, except for the fact that a call is made to tb_init() after the ajax response. This is the thickbox initialise function which attaches its events to your selected elements.

1 comment:

  1. You can easily order your Guild Wars 2 Gold on our website. Guildwars2buygold guarantees quality and quickness.

    ReplyDelete