Search code examples
javascriptjqueryajaxcolorbox

Reloading jQuery Colorbox after pulling data with AJAX


I'm using on my page both colorbox jQuery plugin and AJAX for the asyncronous page loading.

After I pull something from a .php file with AJAX, the content of that .php file doesn't works with colorbox.

$('a.boxed').colorbox({rel: 'Galleria'});
$('a.iframe').colorbox({iframe: true, width: "80%", height: "80%"});

These are the only two rows that I have in my .js file for colorbox (I correctly imported the plugin because it works on other elements not loaded from AJAX). I wanted to create an image that once clicked, opens me a colorbox iframe using this code:

<a href="MYURL" class="iframe"><img src="IMGURL"/></a>

When I click a button on my webpage I use the following code to reload with AJAX:

function showPage(page) { var xmlhttp = new XMLHttpRequest(); // Creo variabile XMLHttpRequest per il caricamento asincrono con AJAX

xmlhttp.onreadystatechange = function() {
    document.getElementById("post-title").innerHTML = page;
    document.getElementById("post-content").innerHTML = xmlhttp.responseText;
}

xmlhttp.open("GET", page + ".php", true);
xmlhttp.send();

}

I read around that I should use the live() method, but I found that with jQuery is deprecated and now there is the on() method.. what a confusion! Could someone help me?


Solution

  • Try this:

    function showPage(page) { 
        var xmlhttp = new XMLHttpRequest(); // Creo variabile XMLHttpRequest per il caricamento asincrono con AJAX
    
        xmlhttp.onreadystatechange = function() {
            document.getElementById("post-title").innerHTML = page;
            document.getElementById("post-content").innerHTML = xmlhttp.responseText;
            $('a.iframe').colorbox({iframe: true, width: "80%", height: "80%"});  // <-- add this line
        }
    
        xmlhttp.open("GET", page + ".php", true);
        xmlhttp.send();
    }
    

    If you add the event handlers before loading the new elements, the new ones will not "receive" the event