June 4, 2012

Auto play and stop html5 audio with jquery

Question by Łukasz Borawski

i have a little problem.

I have a facebook like box window on overlay. This box hide when user click like – obviously. I wanna to use audio element when this window is visible and stop audio when this window will be hide.
So this is my html and jquery. Please help me.

<audio id="audio_player" loop="loop">
    <source src="fileadmin/templates/main/crowd.mp3" type='audio/mpeg; codecs="mp3"'>
    <source src="fileadmin/templates/main/crowd.ogg" type='audio/ogg; codecs="vorbis"'>
</audio>

$(document).ready(function(){
function audio_player (){
    if (
        $('fb_like_box').css('display','block')){
            $('audio').each(function() {
                var song = $(this);
                    song.play();
                });
    }
    else if (
        $('fb_like_box').css('display','none')) {
            $('audio').each(function() {
                var song = $(this);
                    song.pause();
                });
    }
    else {}
}
});

Answer by Starx

Your code syntactically wrong.

First of all, the following syntax is for assigning value.

$('#fb_like_box').css('display','block')

It assigns the property block to element $('#fb_like_box');

If you want to check it, as that, you have use something like this:

if($('#fb_like_box').css('display') == 'block') {
    // then do something
}

A good way to do what you are attempting is:

if ($('#fb_like_box').is(':visible')) {

    $('audio').each(function() {
        $(this).play();
    });

} else {

    $('audio').each(function() {
        $(this).pause();
    });

}
...

Please fill the form - I will response as fast as I can!