I'm using this function to show youtube videos in a lightbox through Magnific Popup. I get the id
of .video-youtube
links to create a dynamic iframe
for any link.
In this page I have 3 different links and the problem is that the lightbox only shows the last video instead of changing it dynamically depending on which link is clicked. Any hint would be appreciated.
<a id="siTrd7uucW" class="video-youtube" href="#">Click to view video</a>
<a id="reFad8ug77" class="video-youtube" href="#">Click to view video</a>
<a id="sghrd7tu99" class="video-youtube" href="#">Click to view video</a>
(function($) {
$(document).ready(function() {
$(".video-youtube").each(function() {
var id = this.id;
$(window).load(function() {
$('.video-youtube').magnificPopup({
items: {
src: $('<iframe width="560" height="315" src="https://www.youtube.com/embed/' + id + '?autoplay=1" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'),
type: 'inline'
}
});
});
});
});
})(jQuery);
Firstly the window.load
is not necessary. You're running in a document.ready handler, so window.load
will already have fired.
With regard to the issue it's because you're selecting all $('.video-youtube')
elements in the loop. Use $(this)
to only refer to the current instance:
(function($) {
$(function() {
$(".video-youtube").each(function() {
$(this).magnificPopup({
items: {
src: $('<iframe src="https://www.youtube.com/embed/' + this.id + '?autoplay=1" width="560" height="315" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>'),
type: 'inline'
}
});
});
});
})(jQuery);