Play YouTube Links in a Lightbox
Opens links to YouTube videos (with the class "wpide-video-lightbox" or around a thumbnail image) in a large on-page video player, and only contacts YouTube after the click.
Opens WPIDE on
Code
<style>
.wpide-yt-box{position:fixed;inset:0;z-index:100000;display:flex;align-items:center;justify-content:center;padding:20px;background:rgba(0,0,0,.88);}
.wpide-yt-box[hidden]{display:none;}
.wpide-yt-box iframe{width:min(1100px,100%);aspect-ratio:16/9;height:auto;border:0;border-radius:8px;background:#000;}
.wpide-yt-close{position:absolute;top:14px;right:14px;width:46px;height:46px;border:0;border-radius:50%;background:rgba(255,255,255,.15);color:#fff;font-size:28px;line-height:1;cursor:pointer;}
</style>
<script>
(function () {
var box = null, last = null;
function videoId(url) {
var m = /(?:youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/)|youtu\.be\/)([\w-]{11})/.exec(url || '');
return m ? m[1] : null;
}
function close() { if (box) { box.hidden = true; box.querySelector('iframe').src = 'about:blank'; if (last) { last.focus(); } } }
document.addEventListener('click', function (e) {
var link = e.target.closest ? e.target.closest('a[href*="youtu"]') : null;
if (!link || !(link.matches('.wpide-video-lightbox, .wpide-video-lightbox a') || link.querySelector('img'))) { return; }
var id = videoId(link.href);
if (!id) { return; }
e.preventDefault();
last = link;
if (!box) {
box = document.createElement('div');
box.className = 'wpide-yt-box';
box.setAttribute('role', 'dialog');
box.setAttribute('aria-modal', 'true');
box.setAttribute('aria-label', 'Video player');
box.innerHTML = '<iframe title="YouTube video" allow="autoplay; encrypted-media; picture-in-picture; fullscreen" allowfullscreen></iframe><button type="button" class="wpide-yt-close" aria-label="Close video">×</button>';
box.addEventListener('click', function (ev) { if (ev.target === box || ev.target.closest('.wpide-yt-close')) { close(); } });
document.body.appendChild(box);
}
box.querySelector('iframe').src = 'https://www.youtube-nocookie.com/embed/' + id + '?autoplay=1&rel=0';
box.hidden = false;
box.querySelector('.wpide-yt-close').focus();
});
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') { close(); } });
})();
</script>
Notes
Add wpide-video-lightbox to a Button block or link a thumbnail image to a YouTube URL. Videos play from youtube-nocookie.com.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.