Pause youtube video playing when popup hided/closed using javascript

JavaScript Nov 24, 2015

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

Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap