Search code examples
jqueryfancyboxfancybox-2

How to close FancyBox when popup image with link is clicked?


I have a FancyBox, that opens a link when clicked on the popped up image:

$(".fancybox").fancybox({
    afterShow: function () {
        $(".fancybox-image").wrap("<a href='"+$(this.element).attr('name')+"' target='_blank' />");
    }
});

Now, I'd like to close the FancyBox when the photo is clicked so I add closeClick:

$(".fancybox").fancybox({
    closeClick: true,
    afterShow: function () {
        $(".fancybox-image").wrap("<a href='"+$(this.element).attr('name')+"' target='_blank' />");
    }
});

This doesn't work. The link opens fine, but the FancyBox doesn't close.

If I remove aftershow FancyBox closes just fine.

So how can both be achieved with a click?


Solution

  • You can chain several jQuery methods to the same selector, so after .wrap() you could chain an .on() method where you could bind a click event that would trigger the $.fancybox.close() public method, like :

    jQuery(document).ready(function ($) {
        $(".fancybox").fancybox({
            // API options
            afterShow: function () {
                $(".fancybox-image")
                // first method
                .wrap("<a href='" + $(this.element).attr('name') + "' target='_blank' />")
                // second method
                .on("click", function () {
                    $.fancybox.close(true);
                });
            }
        }); // fancybox
    }); // ready
    

    See JSFIDDLE