Zhun Zhun - 5 months ago 36
HTML Question

onclick embeded video , background music stop

My problem is exactly like this post


How to stop music when embedded youtube video starts?


But it doesn't solve my problem.

My html for music :

<audio id="myAudio" autoplay>
<source src="music/Morning-Sun.wav">
</audio>


embed video :

<div class="video">
<div onclick="thevid=document.getElementById('thevideo');
thevid.style.display='block'; this.style.display='none';
document.getElementById('iframe').src =
document.getElementById('iframe').src.replace('autoplay=0','autoplay=1');">
<img style="cursor: pointer;" src="images/video-thumb-2.jpg" alt="Walk Through" />
</div>
<div id="thevideo" style="display: none; width:100%;">
<div class="embed-container">
<iframe id="iframe" width="900" height="506" src="https://www.youtube.com/embed/i5e03Re96wY?rel=0&vq=hd720&color=white&autoplay=0&wmode=transparent&theme=dark;controls=0&amp;showinfo=0"frameborder="0" allowscriptaccess="always" allowfullscreen="true"></iframe>
</div>
</div>
</div>

Answer

First of all, (aside from boohiss for having background music), you are better off to create a function rather than include a string of javascript in your html. You made the error of not defining 'thevid' as a variable, which i corrected. You weren't calling the audio at any point either to stop it, so i created a variable to find it by id, and pause it on video play.

Naturally my sound is different, and as it is short i have set it to loop, but you can easily amend this.

Hope this helps you out :)

var thevid=document.getElementById('thevideo');
var thumb=document.getElementById('thumb');
var playing = 1;
function playvid(){

thevid.style.display='block'; 
thumb.style.display='none';                    document.getElementById('iframe').src = 
                    document.getElementById('iframe').src.replace('autoplay=0','autoplay=1');
var aud = document.getElementById('myAudio');

aud.pause();
playing = 0;

thevid.onended = function(){
  aud.play();
};
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <audio id="myAudio" autoplay loop> 
      <source src="http://www.rachelgallen.com/monkey.mp3">
 </audio>
 <div class="video">
                <div id="thumb">   
                    <img style="cursor: pointer;" src="images/video-thumb-2.jpg" alt="Walk Through" onclick='playvid();' />
                </div>
                <div id="thevideo" style="display: none; width:100%;">
                    <div class="embed-container">
                        <iframe id="iframe" width="900" height="506" src="https://www.youtube.com/embed/i5e03Re96wY?rel=0&vq=hd720&color=white&autoplay=0&wmode=transparent&theme=dark;controls=0&amp;showinfo=0"frameborder="0" allowscriptaccess="always" allowfullscreen="true"></iframe>
                    </div>
                </div>
            </div>
</body>
</html>