Skip to content Skip to sidebar Skip to footer

Play And Pause With Onclick On The Same Img

The following script is playing a soundfile when i click on a img (onclick). How do i pause it by clicking on the same img? I´ve tried audio.pause(), but it won´t work. functi

Solution 1:

You should rename your function to audioHandler() for example which will handle whether to play or pause your audio.

Create a boolean to remember if your audio was playing or was on pause.

//initial status: audio is not playingvar status = false;
var audio = document.getElementById("myaudio");

functionaudioHandler(){
  if(status == false || audio.paused){
    audio.play();
    status = true;
  }else{
    audio.pause();
    status = false;
  }
}

Solution 2:

Check the media.paused property of your HTMLMediaElement

function play_pause(media) {
    if (media.paused) {
        media.play();
    else {
        media.pause();
    }
}

Use this in the handler on the element you want to control the action

var elm = document.getElementById('play_button'),
    audio =  document.getElementById('myaudio');
elm.addEventListener('click', function (e) {
    play_pause(audio);
});

Post a Comment for "Play And Pause With Onclick On The Same Img"