I’m using JQUERY and Magnific Popup in a django project. When I clicked on any image in the gallery, it always popup the first image instead of the one selected. This is my current code:
Here is the django template
<!-- jQuery library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- Magnific Popup JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/magnific-popup.js/1.1.0/jquery.magnific-popup.min.js"></script>
{% for image in images %}
<div class="image">
<a href="{{ MEDIA_URL }}images/{{ dir }}/{{ image }}">
{% thumbnail MEDIA_ROOT|add:"images/"|add:dir|add:"/"|add:image 300x300 crop="smart" as im %}
<a href="{{ MEDIA_URL }}images/{{ dir }}/{{ image }}" class="image-link">
<img src="{{ im.url }}">
</a>
</a>
<div class="info">
<a href="{{ MEDIA_URL }}images/{{ dir }}/{{ image }} " class="title" >
{{ dir }}
</a>
</div>
</div>
{% endfor %}
Here is the javascript and magnific popup
<script>
$(document).ready(function() {
$(document).on('click', '.image-link',function(e) {
e.preventDefault();
$('.image-link').magnificPopup({
type: 'image',
closeOnContentClick: true,
closeBtnInside: true,
midClick: true,
mainClass: 'mfp-with-zoom mfp-img-mobile',
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0,1] // Will preload 0 - before current, and 1 after the current image
},
image: {
verticalFit: true,
},
zoom: {
enabled: true
},
callbacks: {
beforeOpen: function() {
}
},
}).magnificPopup('open');
});
});
</script>
2
Answers
Add scroll event to initialize magnific popup for all pages.
I think the issue is that you are initializing Magnific Popup for every image link clicked, which would cause it to always open the first image in the gallery.
Try adjusting your JavaScript code like this:
Hope that solves it 🙂