javascriptjqueryhtmlcssfancybox

Load various size images in a fancybox


I have 5-6 images with various sizes like width from 1000px to 1048px and height from 593px to 1736px. But it's not loading small images. I tried to pass the width & height but it's not working.

HTML:

<a class="fancybox" href="images/press/creating websies for NGOS.png" data-fancybox-group="gallery" title="Creating websites for NGOs" data-width="1048" data-height="593">
    <img src="images/press/creating websies for NGOS.png" style="border:0" alt="">
</a>

JQuery:

$(".fancybox").fancybox({
        beforeShow: function () {
        this.width  = $(this.element).data("width");
        this.height = $(this.element).data("height");
        }
});

So how to do it? It will load as per the width & height passed from HTML. Any idea guys?


Solution

  • Part of the problem is the context of this being lost.

    Whenever we use this in a function, the context of this takes that function.

    So we can assign it early : var $this = $(this);


    Edit: Perhaps this.element is a fancybox way to get the element, I don't know, if so, I'm wrong. Nontheless, here's what we can do , if you want to make use of those data height and width attributes:

    $('a.fancybox').on('click', function (e) {
        e.preventDefault(); /* stop the default anchor click */
    
        var $this = $(this); /* register this */
        $.fancybox({
            'content': $this.html(), /* the image in the markup */
            'width': $this.attr("data-width"),
            'height': $this.attr("data-height"),
            'autoDimensions': false,
            'autoSize': false
        });
    
    });
    

    Try this out here


    Also some CSS will help keep the fancybox frame from scrolling ( for this direct image usage )

    .fancybox-inner img {
        display:block;
        width:100%;
        height:100%;
    }