Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pause a YouTube player when hiding the iframe?

I have a hidden div containing a YouTube video in an <iframe>. When the user clicks on a link, this div becomes visible, the user should then be able to play the video.

When the user closes the panel, the video should stop playback. How can I achieve this?

Code:

<!-- link to open popupVid --> <p><a href="javascript:;" onClick="document.getElementById('popupVid').style.display='';">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>  <!-- popup and contents --> <div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">    <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40" frameborder="0" allowfullscreen></iframe>    <br /><br />    <a href="javascript:;" onClick="document.getElementById('popupVid').style.display='none';">   close   </a> </div><!--end of popupVid --> 
like image 974
0161-Jon Avatar asked Dec 29 '11 12:12

0161-Jon


1 Answers

The easiest way to implement this behaviour is by calling the pauseVideo and playVideo methods, when necessary. Inspired by the result of my previous answer, I have written a pluginless function to achieve the desired behaviour.

The only adjustments:

  • I have added a function, toggleVideo
  • I have added ?enablejsapi=1 to YouTube's URL, to enable the feature

Demo: http://jsfiddle.net/ZcMkt/
Code:

<script> function toggleVideo(state) {     // if state == 'hide', hide. Else: show video     var div = document.getElementById("popupVid");     var iframe = div.getElementsByTagName("iframe")[0].contentWindow;     div.style.display = state == 'hide' ? 'none' : '';     func = state == 'hide' ? 'pauseVideo' : 'playVideo';     iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*'); } </script>  <p><a href="javascript:;" onClick="toggleVideo();">Click here</a> to see my presenting showreel, to give you an idea of my style - usually described as authoritative, affable and and engaging.</p>  <!-- popup and contents --> <div id="popupVid" style="position:absolute;left:0px;top:87px;width:500px;background-color:#D05F27;height:auto;display:none;z-index:200;">    <iframe width="500" height="315" src="http://www.youtube.com/embed/T39hYJAwR40?enablejsapi=1" frameborder="0" allowfullscreen></iframe>    <br /><br />    <a href="javascript:;" onClick="toggleVideo('hide');">close</a> 
like image 72
Rob W Avatar answered Oct 13 '22 21:10

Rob W