Pause youtube video playing when popup hided/closed using javascript

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

https://gist.github.com/timersys/99db1a8d2c8db74cb954

Subscribe to Phanindra Mangipudi

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe