Home > Back-end >  How do I get audio to play when I hover over an image?
How do I get audio to play when I hover over an image?

Time:10-07

I'am a complete beginner in coding I was just practicing making a simple prank web page for my nephew (its an inside joke of ours) I know the solution might be easy but I cannot figure it out on account of being a beginner and still learning. I want the audio to play when I hover my mouse on the image and to stop playing when my mouse is out how can I modify my code (given below) to do that?. I tried with the onclick event and it worked. Thank you in advance

</head>
<body>
   <script>
       function play(){
           var audio = document. getElementById("audio")
           audio.play();
       }
   </script>
    <img src="moolikeacow.jpg" value="PLAY" onclick="play()">
    <audio id="audio" src="rickroll.mp3"></audio>
</body>

CodePudding user response:

I refactored your code a bit. First of all moving the script element to the end of the document to make sure that all elements are loaded before referring to them. Second I made event listeners for both click, mouseover and mouseout events. I also added a function for stopping the audio.

<body>
  <img id="img" src="moolikeacow.jpg" />
  <audio id="audio" src="rickroll.mp3"></audio>
  <script>
    var audio = document.getElementById("audio");
    var img = document.getElementById("img");
    
    function play() {
      audio.play();
    }
    
    function stop() {
      audio.pause();
    }
    
    img.addEventListener('click', play);
    img.addEventListener('mouseover', play);
    img.addEventListener('mouseout', stop);
  </script>
</body>

CodePudding user response:

The First Problem That Stopping it to happen is you wrote javaScript top of the html elements as a result javaScript can't grab those elements because those elements created after javaScript Run.

Second Problem is You Added The Click event to image so only if you click it will start the audio not on hove, So you should add the mouseover event listener to make that work

I just wrote a script that works well as you are looking for and with good comments so you can use or learn how it's working

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Audio Player</title>
  </head>
  <body>
    <img
      src="https://27mi124bz6zg1hqy6n192jkb-wpengine.netdna-ssl.com/wp-content/uploads/2019/10/Our-Top-10-Songs-About-School-768x569.png"
      width="300"
      height="300"
      style="object-fit: cover;"
      id="img"
    />
    <audio
      id="audio"
      src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"
    ></audio>
    <!--  Keep Html Elements That need to grab in javaScript always on top of 
    javaScript Code, So It is present to javaScript To Grab & Interact With.-->
    <script>
       <!-- Grabbing HTML Elements in JavaScript to Interact -->
      const img = document.getElementById("img");
      const audio = document.getElementById("audio");
      <!--  listen for a 'mouseover' event in audio element -->
      img.addEventListener("mouseover", () => {
        <!--  when mouseover event happens we play the audio -->
        audio.play();
      });
      <!--  listen for a 'mouseleave' event in audio element -->
      img.addEventListener("mouseleave", () => {
        <!--  when mouseleave event happens we pause the audio and make the audio duration 0 so it again run from start -->
        audio.pause();
        audio.currentTime = 0;
      });
    </script>
  </body>
</html>
hover on the image and just wait for some seconds to see the magic

You Used Inline Event in Image But There is much more things to do with addEventListener method that comes in every element you grab in javaScript. You can give a look at MDN to know more about addEventListener

If Any other things to know please let me know, i enjoy help you

CodePudding user response:

try this:

$('a').hover(function(){
    PlaySound('mySound');// calling playsound function
},function(){
    StopSound('mySound');// calling stopsound function
});

and change your anchor tag like,

<a href="#">Hover Over Me To Play</a>

  • Related