jQuery change content of colorbox

saromba picture saromba · Oct 10, 2011 · Viewed 9.6k times · Source

I tried already questions with simliar titles, but they don't work. (For example: How to load AJAX content into current Colorbox window?)

I have the main page: (including jQuery 1.6.1)

<script type="text/javascript" src="js/jquery.colorbox.js"></script>
<link rel="stylesheet" type="text/css" href="css/colorbox.css" />
<script>
jQuery(function(){
    $("#aLink").colorbox();
    $('#blub a[rel="open_ajax"]').live('click', function(e){
        e.preventDefault();
        var url = $(this).attr('href'); 
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            cache: false,
            beforeSend: function() {
                //$('#cboxContent').empty();
                $('#cboxLoadedContent').empty();
                $('#cboxLoadingGraphic').show();
            },
            complete: function() {
                $('#cboxLoadingGraphic').hide();
            },
            success: function(data) {
                $('#cboxLoadedContent').append(data);

            }
        });
    });
    });
</script>
<a href="1.html" id="aLink">colorbox open</a>

This works fine, the (simple) content of 1.html is loaded in the colorbox:

1.html:

<div id="blub">
    <a rel="open_ajax" href="2.html">Change Content</a>
</div>

Now I want to change the content by klicking on the link. This doesn't work. Ether I get an additional colorbox, or nothing happens.

Thanx!

Answer

uɥƃnɐʌuop picture uɥƃnɐʌuop · Oct 10, 2011

You could use a jquery live() function to watch for clicks on existing and future colorbox links. Also, I recommend that you don't use rel as your selector. That attribute is intended for use in SEO. So in this example I've moved your selector from the rel attribute to the class attribute:

$(document).ready(function() {
    $('a.open_ajax').live('click', function(){
        $.colorbox({
            open:true,
            href: this.href
            //plus any other interesting options    
        });

        return false;
    });
});

Then just make sure that anything that you want to trigger the new colorbox content has the "open_ajax" class and an href. E.G.:

<a class="open_ajax" href="colorboxPage.html">Open</a>

Update for jQuery 1.7+

For jQuery 1.7, since live() has been deprecated, you'll need to do it this way:

$(document).on("click", "a.open_ajax", function() {
    //everything that was in the live() callback above
});