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


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; = state == 'hide' ? 'none' : '';
    func = state == 'hide' ? 'pauseVideo' : 'playVideo';
    iframe.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');


// youtube video div Id hardcoded in above function line #3


Phanindra Mangipudi

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