Magnific-Popup
Magnific-Popup copied to clipboard
Easier YouTube link detection for plug-n-play YouTube overlays
Hey, just thought I'd share this code since it's pretty useful. The current YouTube parsing code in the documentation and the code can't handle video links with extra URL parameters; also can't handle shortened YouTube links.
Here's code that captures ALL clicks on ANY YouTube link (even ones added to the page after loading), and opens them in the lightbox:
$(document).ready(function ($) {
// this captures ALL clicks on youtube links and makes them open in a lightbox instead
$('body').on('click', 'a[href*="youtu"]', function (e) {
e.preventDefault();
e.stopImmediatePropagation();
$(this)
.magnificPopup({
type: 'iframe',
iframe: {
markup: '<div class="mfp-iframe-scaler">'+
'<div class="mfp-close"></div>'+
'<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
'</div>', // HTML markup of popup, `mfp-close` will be replaced by the close button
patterns: {
youtube: {
index: 'youtube.com/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).
id: function(url) {
// parse the id after the v=, but before other URL parameters
var matches = /v=([^&]+)/ig.exec(url) || [];
return matches[1];
},
src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe.
},
youtubeshort: {
index: 'youtu.be/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).
id: function(url) {
var slashPos = url.lastIndexOf('/'),
vidId = url.substr(slashPos);
return vidId;
},
src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe.
}
},
srcAction: 'iframe_src' // Templating object key. First part defines CSS selector, second attribute. "iframe_src" means: find "iframe" and set attribute "src".
}
})
.magnificPopup('open'); // open immediately
return false;
});
});
Thank you for sharing!
Seven years later, this example is still helpful! Thank you @odbol I really appreciate this.