Search code examples
jqueryaudioclick

Jquery play sound and go to next page


I am trying to figure out how to do this, I want the viewer to click on one of the image, which is inside a apDiv box, then after 3 seconds when the audio finishes, the next page will load.

This is the code it does go to next page, but it does not play the sound, if I remove the setTimeout function the sound plays just fine.

Where did I go wrong?

$(function(){
$('#apDiv1').click(

function(){$("#laugh")[0].play();},
function(){setTimeout(function(){window.location = 'page1.html';}, 3900); }
)
 });

Solution

  • Instead of setting a timeout, which could lead to different problems,
    use the audio event listener ended !

    LIVE DEMO

    $(function(){
    
        function playOnClick(){          
            var sound = $("#laugh")[0];     
            sound.addEventListener('ended', function() {        
               window.location = 'page1.html';        
            }, false);          
            sound.play();          
       }
    
       $('#apDiv1').click(function(){
           playOnClick();
       });
    
    });