Sound onHover works But Not Until User Clicks page

27 Views Asked by At
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="div4">
    <img src="image.png" width="262" height="262" alt=""/>
    <audio id="audio">
    <source src="https://css-tricks.com/examples/SoundOnHover/audio/beep.ogg"/>
    </audio>
    </div>

    <script>
     var audio = $("#audio")[0];
     $("#div4").mouseenter(function() {
     audio.play();
     audio.loop = true;
     });
     $("#div4").mouseleave(function() {
     audio.pause();
     });
     </script>

The Onhover works and repeats but Not until the user Clicks somewhere on the page first.

What I'm trying to figure out is how to make the Onhover work right away when the user hovers over it.

1

There are 1 best solutions below

0
Ahmed Shobky On

use $(document).ready() to ensure that the code will execute only after the DOM has finished loading

     $(document).ready(function() {
    var audio = $("#audio")[0];

    $("#div4").mouseenter(function() {
      audio.play();
      audio.loop = true;
    });

    $("#div4").mouseleave(function() {
      audio.pause();
    });
  });