Wednesday, November 23, 2016

Adding a responsive YouTube video in a Foundation Reveal modal

The Foundation framework has a modal plugin called Reveal. It works pretty well and can be combined with their other plugin flex-video in order to create a responsive embedded video in the modal.

In order have the video autoplay when the modal is opened, you need to add the iframe src dynamically using javascript. Initially, set the src of the iframe to the youtube.com embed URL without the video id; if it's blank it will simply load your website in the iframe.

The trigger has a few Foundation-specific attributes to make the modal work. The "data-reveal-id" attribute tells the trigger which modal to open. That modal will have a matching id. Also, make sure to add the YouTube video ID as a "data-video-id" attribute to the trigger, as we will call on it later in the javascript code.

<!-- Trigger to Open Modal -->
<div id="btnPlayVideo" data-reveal-id="myModal" data-video-id="QH2-TGUlwu4"></div>
<!-- Video Modal --> <div aria-hidden="true" aria-labelledby="modalTitle" class="reveal-modal" data-reveal="" id="myModal" role="dialog"> <div class="flex-video"> <iframe allowfullscreen="" frameborder="0" height="315" src="//www.youtube.com/embed/" width="420"></iframe> </div> <a aria-label="Close" class="close-reveal-modal" href="https://www.blogger.com/null">×</a> </div>"

In your javascript, add the code to update the iframe src when the trigger is clicked. You will also need to add code to reset the iframe src. This will make the video stop playing when the modal window is closed.

// Video Modal
$('#btnPlayVideo).click(function(){
   var videosrc = '//www.youtube.com/embed/' + $(this).attr('data-video-id') + '?autoplay=1';       
   $('#myModal iframe').attr('src', videosrc).attr('data-src',videosrc);
});
// clear iframe on close to kill video $(document).on('close.fndtn.reveal', '[data-reveal]', function(){ $('#myModal iframe').attr('src', '//www.youtube.com/embed/'); });