Search code examples
jqueryajaxcolorbox

How to load AJAX content into current Colorbox window?


I'm searching for the answer for three days in a row already. The matter is that I have a page, links on which should load Colorbox with AJAX content that in its turn contains links that should be loaded in the same Colorbox modal window. So far I managed to make it work (partially) by this:

<script type="text/javascript">
    $(document).ready(function(){
        $("a[rel='open_ajax']").live('click', function() {
            $.colorbox({
                href:$(this).attr('href')
            });
            return false;
        });
    });
</script>

It loads a Colorbox window, if I click on a link, but in this window, if I click on its links, it opens another Colorbox window. And I want the content to be loaded within the current one. Will appreciate any thoughts. Thanx!

P.S. Links in the main window:

<a title="Client Details" rel="open_ajax" href="http://localhost/client/details/123">Client Details...</a>

And links in the Colorbox are all the same (it is simply pagination):

<a rel="open_ajax" href="http://localhost/client/details/123/1">1</a>
<a rel="open_ajax" href="http://localhost/client/details/123/2">2</a>
<a rel="open_ajax" href="http://localhost/client/details/123/3">3</a>
<a rel="open_ajax" href="http://localhost/client/details/123/4">4</a>
<a rel="open_ajax" href="http://localhost/client/details/123/5">5</a>

Solution

  • If you need to load the content into the same Colorbox rather than opening a new instance, I would start by making sure that the event handler context to open the Colorbox was exclusive and not hooked onto the 'open_ajax' elements in the Colorbox.

    Something like this:

    <script type="text/javascript">
        $(document).ready(function(){
            $("a[rel='open_ajax']:not(#colorbox a[rel='open_ajax'])").live('click', function() {
                $.colorbox({
                    href:$(this).attr('href')
                });
                return false;
            });
        });
    </script>
    

    If the above does not work try making the selector more specific/unique.

    Then AJAX in the new content directly into the Colorbox you already have open.

    Something like this:

    $('#cboxLoadedContent a[rel="open_ajax"]').live('click', function(e){
        // prevent default behaviour
        e.preventDefault();
    
        var url = $(this).attr('href'); 
    
        $.ajax({
            type: 'GET',
            url: url,
            dataType: 'html',
            cache: true,
            beforeSend: function() {
                $('#cboxLoadedContent').empty();
                $('#cboxLoadingGraphic').show();
            },
            complete: function() {
                $('#cboxLoadingGraphic').hide();
            },
            success: function(data) {                  
                $('#cboxLoadedContent').append(data);
            }
        });
    
    });