Snorlax
Snorlax

Reputation: 4755

Pausing audio on Div hover

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>

Upvotes: 1

Views: 117

Answers (3)

Cedric Ipkiss
Cedric Ipkiss

Reputation: 6337

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

Upvotes: 1

Cymen
Cymen

Reputation: 14419

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/

Upvotes: 3

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

$(document).ready(function(){
var audio = $("#audio-1")[0];
$(".box").hover
(function() {audio.play();});
});

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

Upvotes: -1

Related Questions