Search code examples
javascriptjqueryhtmljquery-pluginsfancybox

How to insert alt tag for fancy box images [ fancyBox3 ]?


We are using http://fancyapps.com/fancybox/3/ . And this fancybox is working good , except this is not showing img alt tag by default . Even in the documentation also it is not correctly described http://fancyapps.com/fancybox/3/docs/ .

This is our html structure , in this we are mentioning alt tag both in a , and img . But nothing seems to work .

<a data-fancybox="gallery" class="img-1" data-caption="First img" href="img.jpg" data-alt="first img"  data-options='{"alt" : "First img"}'><img src="img.jpg"  alt="First img" class="gallery-fac"></a>

<a data-fancybox="gallery" class="img-2" data-caption="second img" href="img-2.jpg" data-alt="second img"  data-options='{"alt" : "Second img"}'><img src="img-2.jpg"  alt="second img" class="gallery-fac"></a>

$("[data-fancybox]").fancybox({
            thumbs : {
                autoStart : true
            },

 });

We found one solution

 beforeShow : function() {
        var alt = this.element.find('img').attr('alt');

        this.inner.find('img').attr('alt', alt);

       }

But this solution is not working ,So we are searching for solution and got some but that are old .

So if anyone know how to do it , please help to solve.


Solution

  • Simply use afterLoad callback to get clicked element (current.opts.$orig). Then get value for alt attribute (in this sample, I am getting from thumbnail image) and set for the image:

    $('[data-fancybox="images"]').fancybox({ 
      afterLoad : function(instance, current) {
        current.$image.attr('alt', current.opts.$orig.find('img').attr('alt') );
      }
    });
    

    Demo - https://codepen.io/anon/pen/QOBgqz?editors=1010

    btw, is this really important for you? If image does not get loaded, then error message will be displayed and user will not see this alternative text anyway.