Search code examples
javascriptjquerymagnific-popup

Is it possible to set captions for each image when initializing a gallery?


Using magnific popup, is it possible to set captions for each image when initializing a gallery via javascript? There isn't a DOM element for each image, so it's not possible to use the title attribute (or any other attribute) as a pointer to the caption.

$('#my-gallery').magnificPopup({
    items: [
        {
            src: 'image.jpg',
            title: 'Some Title'
        },
        {
            src: 'image2.jpg',
            title: 'Some Other Title'
        }
    ],
    gallery: {
        enabled: true
    },
    type: 'image'
});

Solution

  • You could pass the following parameters to add a caption to your image as per magnific popup documentation (http://dimsemenov.com/plugins/magnific-popup/documentation.html#image-type):

    $('#my-gallery').magnificPopup({
        items: [
            {
                src: 'image.jpg',
                title: 'Some Title'
            },
            {
                src: 'image2.jpg',
                title: 'Some Other Title'
            }
        ],
        gallery: {
            enabled: true
        },
        type: 'image',
        image: {
           markup: '<div class="mfp-figure">'+
                '<div class="mfp-close"></div>'+
                '<div class="mfp-img"></div>'+
                '<div class="mfp-bottom-bar">'+
                  '<div class="mfp-title"></div>'+
                  '<div class="mfp-counter"></div>'+
                '</div>'+
              '</div>', // Popup HTML markup. `.mfp-img` div will be replaced with img tag, `.mfp-close` by close button
    
             tError: '<a href="%url%">The image</a> could not be loaded.' // Error message
       }
    });
    

    Here is a working jsfiddle: https://jsfiddle.net/wmboxLfr/3/

    Note the key thing here is that the image mark up has 'mfp-title', and the items passes title as parameter. Cheers!