Search code examples
jqueryfancyboxhref

Fancybox Download Image


I am trying to make a download button for the image you're currently viewing in Fancybox. I thought it would be a easy thing to do because the url is already stored in the <img> tag so I thought I could just re-use that for the link.

I even tried to find the <img>'s src in fancybox and then .append it to the href of the link (<a> tag). I just lack the jQuery skills to get it done.

To fancybox.js I've added the <a> tag:

<img class="fancybox-image" src="image.jpeg" alt="" />
<a href="" class="test">Download</a>

I tried to copy-and-paste the image.jpeg like so but that didn't work:

var href = $('.fancybox-image').attr('href');
$('a.test').attr('href', href );

Solution

  • The jQuery way

    This answer shows how to accomplish this using standard jQuery methods, correcting the code OP has given. See also Janis's answer to see how this can be done using Fancybox.

    The code you posted here doesn't work because there is no href attribute in the <img> tag. You should use the src attribute instead:

    var href = $('.fancybox-image').attr('src');
    $('a.test').attr('href', href );
    

    However, this will work only if there is only one image with class .fancybox-image. If you have multiple images in your gallery, use the following approach instead:

    $('.fancybox-image').each(function (){
        var href = $(this).attr('src');
        $(this).next("a").attr("href", href);
    });
    

    jsFiddle here