Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto play and stop html5 audio with jquery

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 {}
}
});
like image 200
Lukas Avatar asked Jun 04 '12 08:06

Lukas


2 Answers

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();
    });

}
like image 158
Starx Avatar answered Nov 09 '22 04:11

Starx


try something very basic like

$(document).ready(function(){
  $('audio')[0].play();
}

If this runs, than at least you know you are on the right track. Once you know you can play it, add the conditionals, and then test that they are working.

like image 25
Last Rose Studios Avatar answered Nov 09 '22 02:11

Last Rose Studios