Fancybox with VideoJS – ES6

We are going to write a plugin which shows youtube videos using videojs inside a fancybox popup. You will need

  • jQuery
  • Fancybox
  • VideoJS
  • VodeJS Youtube

VideoJS:

//cdnjs.cloudflare.com/ajax/libs/video.js/5.8.0/alt/video-js-cdn.min.css
//cdnjs.cloudflare.com/ajax/libs/video.js/5.8.0/video.min.js
//cdnjs.cloudflare.com/ajax/libs/videojs-youtube/2.0.8/Youtube.min.js

Fancybox:

//cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js

Scriptjs

npm install --save-dev scriptjs

The whole code is

$(() => {
   const $videoLinks = $('.video-item-link');
   if ($videoLinks.length) {
      
      const fancyboxConfig = {
         closeBtn: false,
         padding: 0,
         margin: [20, 60, 20, 60], // Increase left/right margin
         width: '100%',
         height: '100%',
         helpers: {
            overlay: {
               background: 'rgba(0, 0, 0, 0.9)'
            }
         }
      };
      
      $videoLinks.click((e) => {
         e.preventDefault();

         const $this = $(e.currentTarget);
         const w = $this.data('width');
         const h = $this.data('height');
         const videoId = $this.data('id');
         const url = $this.attr('href');

         $.fancybox.open($.extend(fancyboxConfig, {
            content: `
            <video id="${videoId}" class="video-js vjs-default-skin"
               controls preload="auto" width="${w}" height="${h}"
               data-setup='{
               "controls": true,
               "autoplay": true,
               "preload": "auto",
               "techOrder": ["youtube"] }'>
               <source src="${url}" type='video/youtube'>
            </video>
            `,
            afterShow: () => {
               // do this for the dynamically loaded video
               const player = window.videojs(`${videoId}`, {});
               player.on('ended', () => {
                  $.fancybox.close(true);
               });
            },
            beforeClose: () => {
               // if you do not do this the video will keep downloading in the background
               window.videojs(`${videoId}`).dispose();
            }
         }));
      });
   }
});