I have a modal that a youtube is embedded in the container. When I click on “X” to close the modal, the youtube video still plays. I would like to be able to stop the video upon closing. The below JS is for closing the modal when clicking outside of the container.
Is there a way to stop the video thru JS when closing the modal.
It partial works. If I just use your JS and I use my modal code between the div’s, the video stops playing when I click the “X” abut then if I want to play the video again, when you click it only shows the grayed screen with only the “X” showing and no video.
When I use all of your code, when I click to see the video, no video appears.
Note the enablejsapi=1 parameter in the iframe URL. Then include the API like so:
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var modal = document.querySelector('.modal')
var closeBtn = document.querySelector('.close')
var player
// Once the API is ready, create a player object for the
// iframe with the id="player"
var onYouTubeIframeAPIReady = function () {
player = new YT.Player('player')
}
// When the close button gets clicked, check if the player
// got already initialised, and if so, pause it.
closeBtn.addEventListener('click', function () {
modal.style.display = 'none'
if (player) {
player.pauseVideo()
}
})
</script>
This way you have full control over the player, and don’t have to load the iframe anew each time you open the modal.
Thanks, that code works good. So the above code on clicking outside of the modal doesn’t work which is fine, but want to make sure that is correct where you only close it with the “X”/
This code does close it but the audio still continues to play (video is gone)which was the purpose of my original post. In a perfect world it would be good to have both. (“X” closes it down and clicking outside the container closes it down)
What @m_hutley said… my snippet was just to demonstrate how to generally pause the video, but you can of course apply that at any other point too. E.g. make the closing function reusable by assigning it to a variable:
var closeModal = function () {
modal.style.display = 'none'
if (player) {
player.pauseVideo()
}
}
closeBtn.addEventListener('click', closeModal)
// Or inside another event handler simply call:
// closeModal()