Hi,
I have made a personal website with numerous modals that include youtube videos. Unfortunately when the modal is closed, the youtube video continues to play (i.e. can still be heard). Hoping someone can help with script to prevent this. There is a fair bit of code available on google but I haven’t been able to adapt it. I used a W3schools modal and styled it a little, mainly just by making the modal box transparent and changing the close button (looked pretty nice and sparse in the end I thought, just in case anyone would like to use it). The code below is simplified but has a few of the modals/videos and demonstrates the issue. I should confess that while I have learned a fair amount of HTML and CSS, I’m yet to embark on javascript so I’m out of my depth here but would be fantastic if someone can help to get this particular problem out of the way. Many thanks.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<style>
/*Removed modal box, i.e. background and border*/
.modal-content {
background-image: transparent;
margin: 15% auto; /*5% from top and centered*/
padding: 0px 0px 0px 0px;
width: 560px;
height: 315px; /*Matches width and height of iframe but made transparent*/
}
.close {
color: #aaa;
float: right;
font-size: 18px;
color: #FFFFE0;
}
.close:hover, .close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
<body>
<!--trigger modal-->
<a class="dropdownlink" onclick="document.getElementById('id01').style.display='block'">Coming Down From Rising Fawn</a>
<!--modal-->
<div id="id01" class="w3-modal w3-animate-opacity">
<!--modal content-->
<div class="modal-content">
<span onclick="document.getElementById('id01').style.display='none'" class="close">×</span>
<iframe width="560" height="315" src="https://www.youtube.com/embed/NCHEpoob-pE" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen>
</iframe>
</div>
</div>
<br/>
<br/>
<!--trigger modal-->
<a class="dropdownlink" onclick="document.getElementById('id02').style.display='block'">Give Me Back My 15 Cents</a>
<!--modal-->
<div id="id02" class="w3-modal w3-animate-opacity">
<!--modal content-->
<div class="modal-content">
<span onclick="document.getElementById('id02').style.display='none'" class="close">×</span>
<iframe width="560" height="315" src="https://www.youtube.com/embed/0VMvU7NYWd0" frameborder="0" gesture="media" allow="encrypted-media" allowfullscreen>
</iframe>
</div>
</div>
<script>
/*Get modal*/
var modalA = document.getElementById('id01');
var modalB = document.getElementById('id02');
/*Close on clicking outside modal*/
window.onclick = function(event) {
if (event.target == modalA) {
modalA.style.display = "none";
}
if(event.target == modalB) {
modalB.style.display = "none";
}
}
</script>
</body>
</html>