1

I managed to get the audio to play on hover but I can't get it to pause when my mouse leaves the area.

FIddle: https://jsfiddle.net/jzhang172/nLm9bxnw/1/

$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {
    audio.play();
  },
(function(){
 audio.stop();
});
});
.box{
  height:500px;
  width:500px;
  display:flex;
  justify-content:center;
  align-items:center;
  font-size:25px;
  color:white;
  background:black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio controls id="audio-1">
  <source src="http://www.stephaniequinn.com/Music/Allegro%20from%20Duet%20in%20C%20Major.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

<div class="box">
If you Hover me, the song will play!
</div>
Snorlax
  • 4,425
  • 8
  • 37
  • 68

3 Answers3

3

You need to use audio.pause() not .stop(). For example:

$(document).ready(function(){
  var audio = $("#audio-1")[0];
  $('.box').on({
    mouseenter: function() {
      audio.play();
    },
    mouseleave: function() {
      audio.pause();
    }
  });
});

This will resume where it stopped. If you want to start from the beginning, as one of the other answers suggested, you would need to include audio.currentTime = 0; before the start or after the pause invocation.

JSFiddle: https://jsfiddle.net/nLm9bxnw/7/

Cymen
  • 14,079
  • 4
  • 52
  • 72
1

stop really isn't a javascript method for audio and video file manipulation. Rather use one of the following:

audio.pause();
audio.currentTime = 0;

See This thread

Community
  • 1
  • 1
Cedric Ipkiss
  • 5,662
  • 2
  • 43
  • 72
-1
$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {audio.play();});
});

https://jsfiddle.net/Cuchu/Ln8q8739/

Maxi Schvindt
  • 1,432
  • 1
  • 11
  • 20