How to include caption for gallery using magnific popup?

user3155730 picture user3155730 · Dec 25, 2015 · Viewed 11.1k times · Source

I am trying to include a caption on the actual webpage under the image while using the magnificence popup gallery. Using a div and class caption or carousel-caption, I am unable to do so without the images in the gallery stacking vertically one by one. How can I do this?

<a href="img/base/ggg.PNG" title="HELLO" class="chicken">
  <img src="img/base/pop.PNG" alt="remember your alt tag" />
</a>

$(document).ready(function() {
      $('.chicken').magnificPopup({ 
         type: 'image',
         gallery:{enabled:true}
         // other options here
         // end each line (except the last) with a comma
      });
   });

js fiddle: https://jsfiddle.net/sb4btox7/

Answer

JessycaFrederick picture JessycaFrederick · Jan 2, 2016

Since I don't yet have enough reputation points to comment, I'm commenting here, in addition to providing a solution.

Comment: JSFiddle isn't working with your http:// images because JSFiddle is trying to serve them from https://

Solution:

You are halfway there. There are 2 parts to making the captions work.

  1. You correctly have put the link in the anchor tag and not the image tag
  2. You must specify your title source in your initialization script like this.

    $(document).ready(function() {
        $('.chicken').magnificPopup({ 
            type: 'image',
            gallery:{enabled:true},
            type: 'image',
            image: {
                titleSrc: 'title' 
                // this tells the script which attribute has your caption
            }
        });
    });
    

The script then automatically writes your caption to its div labeled class="mfp-title"

BONUS Solution: I needed my lightbox image to open in a new window for users on their phones to zoom in, so I added this after the first titleSrc declaration:

    titleSrc: 'title',
    titleSrc: function(item) {
        return '<a href="' + item.el.attr('href') + '">' + item.el.attr('title') + '</a>';
        }

This information is in the documentation: http://dimsemenov.com/plugins/magnific-popup/documentation.html in the "Image Type" section