Ninja
Ninja

Reputation: 67

Toggle audio in JS

I have code that when and image is clicked by the user, it plays an audio file.

    <script>
  function playSong(){
       var audio = document.getElementById("suess");
       audio.play();
                 }
   </script>
<input type="image" src="suessical.jpg" onclick="playSong()" alt="Click to play a song from the show!">
<audio id="suess" src="http://ninjareviews.hostreo.com/Seussical-the-Musical-Green-Eggs-and-Ham.mp3"></audio>\

How would I modify the script so that when the same image is clicked again, the music pauses and resumes when clicked again? Would I have to use JQuery or can I use JS?

Upvotes: 1

Views: 445

Answers (2)

AlexandruB
AlexandruB

Reputation: 688

You access on audio object the information if it is paused or not.

if (audio.paused) { audio.play(); } else { audio.pause(); }.

More info: http://www.w3schools.com/tags/ref_av_dom.asp

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

Used a toggle based on the paused property:

function playSong(){
   var audio = document.getElementById("suess");
   if (audio.paused) audio.play();
   else audio.pause();
}

Upvotes: 1

Related Questions