Pause youtube video playing when popup hided/closed using javascript
Use Case
When a Youtube video embed in a div / iFrame when it is hidden using popup or iFrame, Video continues to play in background in order to pause/stop following code snippet will be helpful
Visualforce page/ HTML Page
Javascript
function toggleVideo(state) {
// if state == 'hide', hide. Else: show video
var div = document.getElementById("popupVid");// youtube video div Id hardcoded here
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":""}', '*');
}
Invoke
toggleVideo('hide');
// youtube video div Id hardcoded in above function line #3
Credits