Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;});
});
like image 551
rafleo Avatar asked Dec 12 '22 07:12

rafleo


2 Answers

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;
});
like image 189
Jack Avatar answered May 10 '23 05:05

Jack


You need to remove the docReady function from within the docReady function. In jQuery, this:

$(function() {
    //your docReady code
});

is the shorthand form of this:

$(document).ready(function() {
    //your docReady code
});

When you have embedded docReady code, the embedded docReady code is queued and executed after the current docReady code has completed. Observe:

$(document).ready(function() {
        $(function() {
            alert("FIRST in code, but executed SECOND");
        });

        alert("SECOND in code, but executed FIRST");
});

To be honest, I am not certain if that will solve your issue, but it can lead to strange issues in any case.

like image 29
uɥƃnɐʌuop Avatar answered May 10 '23 06:05

uɥƃnɐʌuop