Confucius
Confucius

Reputation: 69

Play Audio using jQuery

I have a list of Sound Icon images in different divs on my website. I'm trying to use jQuery to play/pause different songs on mouseenter and mouseleave dependent on which icon is hovered over. I have the first item working but am having problems understanding the best way to get the rest working. Any help with this would be really appreciated. Thanks.

<audio preload="auto" id="songOne">
  <source src="audio/****.mp3" controls></source>
  <source src="audio/****.ogg" controls></source>
  <source src="audio/****.wav" controls></source>
  Your browser isn't invited for super fun audio time.
</audio>

$(document).ready(function(){
  var song1 = $("#songOne")[0];
  $(".topDownloads img").first().mouseenter(function() {
    song1.play();
    $(".topDownloads img").mouseleave(function() {
      song1.pause();
    });
  });
});

Upvotes: 1

Views: 2035

Answers (1)

Lix
Lix

Reputation: 48006

What you might be able to do is embed the specific song object name onto the element which the user is clicking. For example, assuming the .topDownloads element is a div:

<div class="topDownloads">
  <img data-song="someSong" src="..." />
  <img data-song="anotherSong" src="..." />
</div>

You can now use that data attribute in your mouse event callback. Store all your song objects in a key->value object and retrieve them from the data attribute.

// setting up key->value song pairs
var songs = {
  'someSong':$("#someSong")[0],
  'anotherSong':$("#anotherSong")[0],
};

$(".topDownloads img").hover(function() {
   // extract song key name
   var songItem = songs[$(this).data('song')];
   songItem.play();
},function() {
   // extract song key name
   var songItem = songs[$(this).data('song')];
   songItem.pause();
});

Notice that I've used the .hover() function instead of .mouseenter() and .mouseleave(). This function receives two functions as parameters, the first function is triggered when the mouse enters the element, and the second function executes when the mouse leaves the element. I think this syntax is a bit easier to work with and makes more sense.

Upvotes: 2

Related Questions