How to pause a YouTube player when hiding the iframe? How to pause a YouTube player when hiding the iframe? javascript javascript

How to pause a YouTube player when hiding the iframe?


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>


Here's a jQuery take on RobW's answer for use hiding /pausing an iframe in a modal window:

    function toggleVideo(state) {        if(state == 'hide'){            $('#video-div').modal('hide');            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');        }        else {            $('#video-div').modal('show');            document.getElementById('video-iframe'+id).contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');        }    }

The html elements referred to are the modal div itself (#video-div) calling the show / hide methods, and the iframe (#video-iframe) which has the video url as is src="" and has the suffix enablejsapi=1? which enables programmatic control of the player (ex. .

For more on the html see RobW's answer.


Here is a simple jQuery snippet to pause all videos on the page based off of RobW's and DrewT's answers:

jQuery("iframe").each(function() {  jQuery(this)[0].contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')});