Search code examples
javascriptjqueryhtmlcolorbox

Opening an existing jQuery lightbox gallery from a link


I have an existing jQuery colorbox gallery that works fine when I click any of the 4 images which is initialized on document ready with:

$(document).ready(function () {
    if ($('.gallery-thumbnail').length > 0) {
        $('.gallery-thumbnail').colorbox({ rel: 'gallery-thumbnail', transition: 'fade' });
    }
});

I also have a link in the page, which I would like to also open this same gallery of images. I thought I would be cute and try to just replicate a user clicking one of the images with $('.gallery-image').first().find('a').click(); which works perfectly and opens the image gallery when I type it in the Chrome Inline Console and hit Enter, but when it is run from the code, it just pops the gallery open with the orange loading GIF which spins endlessly. After that I tried having an onclick handler directly on the HTML anchor which had the code $('.gallery-thumbnail').colorbox({rel: 'gallery-thumb', transition: 'fade' }); which resulted in the same endless loading GIF as before. To ensure that I wasn't going crazy, I hooked the OnClick event handler to a function which runs this code:

function showColorbox() {
    $('.gallery-thumbnail').each(function () {
        $(this).addClass('test');
    });
    $('.test').colorbox({rel: 'gallery-thumb', transition: 'fade' });
}

Unfortunately, I still end up with the endless loading colorbox, but I verified that my image anchors all had the class 'test'. Throughout this whole thing - I have also verified that there are no JS errors in the console. Any help would be greatly appreciated.


Solution

  • There's an FAQ entry for this: http://www.jacklmoore.com/colorbox/faq/#faq-click

    Create a separate link for opening a gallery

    Lets say you've assigned Colorbox to a set of links in your document, but you also want to have an "Open Gallery" link that opens the first item in your set. When "Open Gallery" is clicked, you want to prevent the default action, then trigger a click event on that first set item.

    var $gallery = $("a[rel=gallery]").colorbox();
    $("a#openGallery").click(function(e){
        e.preventDefault();
        $gallery.eq(0).click();
    });