Search code examples
jquerymagnific-popup

Open all images on page with magnific popup


I want to enable magnific popup on all images on my page. I do not want to alter the DOM (surround my image tags with anchors like suggested in the documentation).

My DOM is something like

<div id="content">
  <img src="img/mw1.png" class="figure-img img-fluid">
  <img src="img/mw2.png" class="figure-img img-fluid">
  <img src="img/mw3.png" class="figure-img img-fluid">
</div>

And the JS I have:

var $imgs = [];
$('img').each(function(idx) {
  var obj = {
    src: $(this).attr('src')
  }
  $imgs.push(obj);
  var elem = $(this);
  $(this).click(function() {
    console.log('clicked on img', idx);
    $('#content').magnificPopup('open', idx);
  });
});

$('#content').magnificPopup({
  items: $imgs,
  type: 'image',
  gallery: {
    enabled: true
  },
});

https://www.codeply.com/go/A2yRWr4bDi No matter which image i click, always, the first gets opend. I want it exactly like it is, just with the difference that the clicked image gets opened first.


Solution

  • Looks like there's a bug in the magnific-popup code where it never passes that index along.

    In v1.1.0 jquery.magnific-popup.js, line 931 (unmin'd), add:

    itemOpts.index = index;  // add this line
    mfp._openClick({mfpEl:items}, jqEl, itemOpts);  <-- before this line
    

    and it will work fine.

    However, this will mean you'll need a local copy of the file and min it yourself (locally) until the author can update.