user3013881 user3013881 - 1 month ago 22
jQuery Question

Play different sounds on click menu

I'm working on a project where I need to play a diferent audio file for every div on a menu.

I'm using the following code:

$(document).ready(function() {
var playing = false;
$('.punt').click(function() {
if (playing == false) {
$(this).play();
playing = true;
} else {
$(this).pause();
$(this).currentTime=0;
playing = false;
}
});
});


And HTML:

<div class="menu">
<ul>
<li><div class="punt primertf">Transecte 1<audio id="player" src="so/itinerari.mp3"></audio></div></li>
<li><div class="punt segontf">Transecte 2<audio id="player" src="so/fontibonun.wav"></audio></div></li>
<li><div class="punt tercertf">Transecte 3<audio id="player" src="so/fontibondos.wav"></audio></div></li>
<li><div class="punt quarttf">Transecte 4<audio id="player" src="so/fontibontres.wav"></audio></div></li>
<li><div class="punt cinquetf">Transecte 5<audio id="player" src="so/fontibonquatre.wav"></audio></div></li>
</ul>
</div>


If instead of (this) I use a different class for each one it works, but I think it can be simple than this way. What I'm doing wrong?

Joe Joe
Answer

The reason it isn't working is that you're confusing $(this) (jQuery object) and this (DOM element). The jQuery object doesn't have play/pause methods or a currentTime property. Below is working code:

$(document).ready(function() {  
    var playing = false,
        audioPlayers = $('.punt audio');
    $('.punt').click(function() {  
        if (playing == false) {  
            $(this).find('audio').get(0).play();  
            playing = true;  
        } else {  
            audioPlayers.each(function(){
                this.pause();
                this.currentTime=0;
            });  
           playing = false;  
        }  
    });  
});

audioPlayers is a cached jQuery object containing all the menu audio tags. When a menu item is clicked we do a check to see whether any audio is playing. If it isn't then we play the selected menu's audio by finding the child audio tag, getting the matched DOM element using .get() and then using .play().

If audio is already playing we loop through every audio tag using .each() then pause and reset the current time of each one. this can be used within the .each() loop as it references the audio tag directly.

Here's a working demo: http://jsfiddle.net/kpk6y1dr/ (I've also removed the duplicate ids)

Comments