1

I am learning HTML-CSS-JS by doing some little exercises of my own. I have created a little code that plays an mp3 audio when I click on an image:

 <html>
  <head>
    <title>Image audio exercise</title>
  </head>
  <body>
    <script>
      function play(){
         var audio = document.getElementById("audio");
         audio.play();
      }
    </script>
    <img src="img.gif" onclick="play()">
    <audio id="audio" src="sound.mp3" ></audio>
  </body>
 </html> 

I would like to be able to play a different audio file when the click is outside the image. Is there a simple way to do it? Maybe an if-else statement?

K.Ariche
  • 1,188
  • 3
  • 14
  • 29
Gigi
  • 57
  • 1
  • 10
  • 1
    Check this issue (http://stackoverflow.com/questions/18893144/javascript-detect-click-event-outside-of-div) maybe can help you :) – ayxos Mar 17 '17 at 11:00

2 Answers2

3

You can do something like this. Just a simple check to see if you clicked on the image or the document.

<html>
  <head>
    <title>Image audio exercise</title>
  </head>
  <body>

    <img id="theImage" src="img.gif">
    <audio id="audio" src="sound.mp3" ></audio>

    <script>
      var audio = document.getElementById("audio");
      var img = document.getElementById("theImage");

      document.addEventListener("click", function(e){
         if( e.target === img ){
           audio.src = "sound.mp3";
           audio.play();
         }
         else{
           audio.src = "sound2.mp3";
           audio.play();
         }
      },false);
    </script>

  </body>
</html>
Hemant Parashar
  • 3,684
  • 2
  • 16
  • 23
0

Do something like this:

document.onclick = function(e) {
if (e.target != document.getElementById('clickMe')) {
    document.getElementById('audio').play();
}else {
    document.getElementById('audio2').play();
}

}

Tommy Nguyen
  • 96
  • 1
  • 5