jQuery HTML Element How to - Play sound and go to next page with audio element








Question

We would like to know how to play sound and go to next page with audio element.

Answer


<!DOCTYPE html>
<html>
<head>
<script
  src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head><!--  w  ww .  j a v a 2  s.  c o m-->
<body>
  <button id="apDiv1">CLICK</button>
  <audio id="laugh">
    <source
      src="http://upload.wikimedia.org/wikipedia/commons/a/a2/Barking_of_a_dog.ogg"
      type="audio/ogg">
    Get a new browser!
  </audio>
  <script>
$(function(){
    function playOnClick(){
      var sound = $("#laugh")[0];     
      sound.addEventListener('ended', function() {        
         // window.location = 'page1.html';        
      }, false);
      sound.play();
   }
   $('#apDiv1').click(function(){
       playOnClick();
   });
});
</script>
</body>
</html>

The code above is rendered as follows: