Search code examples
jquerycolorbox

Dynamically loaded links don't trigger ColorBox on click, but on second click


I have a problem which I can't seem to be figuring out:

I load content dynamically using jQuery to a TinyScrollbar. The content contains links that should fire up ColorBox. For the links to work, I used jQUery's delegate. But, after loading content, my ColorBox only opens if I click the link twice.

(I suppose, one to make jQuery realise that there's a matching element, second time to execute the delegate function.)

Here's my code:

$(document).ready(function() {
    var main = $('#main');
    main.tinyscrollbar();

    $(function(){
        $(window).bind( 'hashchange', function(e){
            var hash = location.hash;

            if (hash != '' && hash != ' ' && hash != 'undefined') {
                var urlToLoad = hash;
                $('.overview').load(urlToLoad, function(response, status, xhr) {
                  urlToLoad = "";
                  main.tinyscrollbar_update();
                });
            }
         });
        $(window).trigger( 'hashchange' );
     });

    $(document).delegate("a.video", "click", function(e){$(this).colorbox({iframe:true, innerWidth:700, innerHeight:394, fastIframe:false, transition:"none"});return false; });
    $(document).delegate("a.img", "click", function(e){$(this).colorbox({transition:"none"});return false;});
});

Solution

  • This makes sense because you are only binding the colorbox click event and settings data during the first click. It isn't until you click again that you trigger the click event and open colorbox. Since you are already using your own click events, my suggestion would be not to bind colorbox to anything, just call it directly when needed. Example:

    $(document).delegate("a.img", "click", function(e){
        $.colorbox({transition:"none", href:this.href});
        return false;
    });