paulirish / lite-youtube-embed

A faster youtube embed.
https://paulirish.github.io/lite-youtube-embed/
Other
5.84k stars 271 forks source link

Stop video after closing modal #144

Closed AttilioIurlaro closed 7 months ago

AttilioIurlaro commented 1 year ago

I'm using youtube-lite inside the modal. How can I stop the youtube video after closing the modal?

summerregina commented 1 year ago

Did you find a solution? I tried connecting my closeModal to this solution when clicked off the modal - https://stackoverflow.com/questions/15164942/stop-embedded-youtube-iframe - but can't get it to work either

thisisjamessmith commented 1 year ago

Here's my solution to this, seems to work fine. Note that you need the params="enablejsapi=1" attribute in order to pass the pauseVideo command/event/whatever it's called into the iframe.

<lite-youtube params="enablejsapi=1" videoid="{{ video.youtubeVideoId }}" playlabel="{{ video.title ?? null }}" style="background-image: url('https://i.ytimg.com/vi/{{ video.youtubeVideoId }}/maxresdefault.jpg');"></lite-youtube>
document.querySelector('.js-modalTrigger').addEventListener('click', e => {
    const videoElement = document.querySelector('lite-youtube');
    const iframe = videoElement.querySelector('iframe');

    if (!videoElement.classList.contains('lyt-activated')) {
        // autoplay video when modal is opened
        videoElement.click();
    } else {
        // pause video when modal is closed
        iframe.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*')
    }
});
paulirish commented 7 months ago

@thisisjamessmith's solution looks fantastic. And with new #164 that'll be something like..

document.querySelector('.js-modalTrigger').addEventListener('click', async e => {
    const player = await document.querySelector('lite-youtube').getYTPlayer();
    player.pauseVideo();
});