You can also use the YouTube API to do this, but it will also require re-writing some of your code. I have adapted the linked example for your situation below.
HTML
I have replaced the video with a placeholder div
with the id player
. Once the video is loaded by the YouTube API, it will replace this div
. I have also added the class close
to the span
so we can refer to it by its class instead of the tag, which would allow you to have the X button on modals, but also use span
tags elsewhere without causing conflicts.
<img id="myBtn" src="URL of button here" alt="" style="width: 70px; height:70px;" >
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">x</span>
<div class="videoWrapper">
<p>
<div id="player"></div>
</p>
</div>
</div>
</div>
JavaScript
We need to do a few things:
Load the YouTube API
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
Load the video
var player;
function onYouTubeIframeAPIReady(){
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JY1ddEDcVV0',
rel: '0',
controls: '0',
showinfo: '0'
});
});
Define the stopVideo()
function
function stopVideo() {
player.stopVideo();
}
Call stopVideo()
every time you close the modal. Just simply add it into your "onclick" functions. You can also do these types of functions with jQuery exclusively, which I have shown an example of with the close button.
$(".close").click(function() {
modal.style.display = "none";
stopVideo();
});
JavaScript all together
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var modal = document.getElementById('myModal');
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
$(".close").click(function() {
modal.style.display = "none";
stopVideo();
});
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
stopVideo();
}
}
var player;
$( document ).ready(function() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'JY1ddEDcVV0',
rel: '0',
controls: '0',
showinfo: '0'
});
});
function stopVideo() {
player.stopVideo();
}