Streaming live at 10am (PST)

Stop Playing Youtube Video when Modal is Closed


#1

Greetings Webflow Community,

I’m trying to figure out a way to close/stop a video from playing if the modal is closed because currently the audio still plays if a user closes the modal while video is playing. I’m pretty sure I’ll need some custom code, but not too great at javascript. I tried to go off an older post, but didn’t have much luck

Attached a screenshot of what I have so far using an HTML Embed

and maybe someone can point me in the right direction.

Preview Link - https://preview.webflow.com/preview/winter-takeover?utm_source=winter-takeover&preview=93ba2dd6279b7b26933b1b28d60dcbb3

Would really appreciate anybody’s help.

Please and thanks in advance!


#2

Stop a youtube video with jquery?

Stop embedded youtube iframe?

Stop YouTube video within iFrame on external Button click

Stop all playing iframe videos on click a link javascript


#3

First off, I’d would like to thank @samliew for pointing me in the right direction with those links.

And just in case anyone else is looking for the solution for this, here’s what worked for me…

Ex. HTML Embed Code:

<div id="whateverID">
    <iframe width="640" height="390" frameborder="0" title="YouTube video player" type="text/html" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1"></iframe>
</div>

Pure JS script to be added to Custom Code of page Inside the head tag:

<script>
function callPlayer(func, args) {
    var iframes = document.getElementsByTagName('iframe');
    for (var i = 0; i < iframes.length; ++i) {
        if (iframes[i]) {
            var src = iframes[i].getAttribute('src');
            if (src) {
                if (src.indexOf('youtube.com/embed') != -1) {
                    iframes[i].contentWindow.postMessage(JSON.stringify({
                        'event': 'command',
                        'func': func,
                        'args': args || []
                    }), "*");
                }
            }
        }
    }
}
</script>

Close link URL to be added via Link Settings:

javascript:void callPlayer("stopVideo")

Note. Be sure to add backtick (`) before javascript:…; If not, https:// will be added to URL and it will not work as expected (link will direct users to about:blank page).