Stop Playing Youtube Video when Modal is Closed

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 - Webflow - Winter Takeover

Would really appreciate anybody’s help.

Please and thanks in advance!

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

2 Likes

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).

5 Likes

Is it possible to change the video link from youtube to a self hosted video instead?

@zhadrock

Are you referencing using the video widget? If so, then no. If your asking if it is possible to use custom code to add a video to a modal on a page, then stop it from playing when a model closes; then yes, with custom code. The code here was targeting an embed from Youtube, which has its own player.
.

1 Like