Search the blog

I love Magnific Popup but if you use the gallery feature with the delegate option it does not remove duplicates. This was an issue for me as I was using a carousel that cloned image links and this led to duplicates. Here is how I fixed it.

Each gallery (it works with multiple galleries on the same page) should be wrapped in div.gallery and then each link to a gallery image should be a.img. This allows you to have links in div.gallery that aren’t gallery links.

Your HTML might look like this:

<div class="gallery"> 
    <a class="img" href="image-1.png">Link 1</a> 
	<a class="img" href="image-2.png">Link 2</a> 
	<a class="img" href="image-3.png">Link 3</a> 
	<a href="#">A link that won’t affect the gallery.</a> 
</div>

And here’s the Magnific code, to be called once the document is ready:

$('div.gallery').each(function() {

    var items = [];

    var $gallery = $(this);

    // Get links
    $gallery.find('a.img').each(function() {

        items.push($(this).attr('href'));

    });

    var uniqueItems = [];

    // Remove duplicates
    $.each(items, function(i, el) {

        if($.inArray(el, uniqueItems) === -1) {

            uniqueItems.push(el);

        }

    });

    items = [];

    // Put in Magnific format
    $.each(uniqueItems, function(i, el) {

        items.push({

            src: el,
            type: 'image'

        });

    });

    // Assign an index to each link so the clicked one is shown first
    $gallery.find('a.img').each(function() {

        var $a = $(this);

        $.each(items, function(i, el) {

            if (el.src == $a.attr('href')) {

                $a.data('index', i);

                return;

            }

        });

    });

    $gallery.on('click', 'a.img', function(e) {

        e.preventDefault();

        var $a = $(this);

        $.magnificPopup.open({

            type: 'image',
            items: items,
            gallery: {

                enabled: true

            }

        });

        $.magnificPopup.instance.goTo($a.data('index'));

    });

});
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.