JohnMichael JohnMichael - 6 months ago 25
Javascript Question

Toggle on/off buttons in Javascript

I'm stuck. I've got two buttons with each a single function, one that plays a sound when clicked and one that pauses the sound when clicked. I want to be able toggle between them so I just see one button saying "Sound on" when it's off and vice versa.
Problem is: my Javascript knowhow!

<audio id="spacesound"> </audio>
<button type="button" id="offbutton" class="offbutton" onclick="disableSound()">Sound off</button><br>
<button type="button" id="onbutton" class="onbutton" onclick="reenableSound()">Sound on</button>


These are the buttons, and in case if necessary, the functions they call.

//it plays on auto when the page is loaded
myAudiothree = new Audio('media/deepspace.mp3');
myAudiothree.loop = true;
myAudiothree.play();

//continue sound
function reenableSound()
{
myAudiothree.play();
}

//pause sound
function disableSound()
{
myAudiothree.pause();
}


There might be some CSS code for this but I'd much rather have it in JS, thank you!

Answer

The solution is simple "save" the actual state in a variable...

var isPlaying=false;

function playOrPause()
{
  if(isPlaying)
  {
    myAudiothree.pause();
    isPlaying=false;
  }else
  {
    myAudiothree.play();
    isPlaying=true;
  }
}

now you only have one function instead of two.

Edit:

I created a snipped for you, for showing how to change the button text also.

var isPlaying=false;

$('#myButton').click(function(){
    var $this = $(this);
  if(isPlaying)
    {
      isPlaying=false;
      $this.text('start'); 
      
      }else{
        isPlaying=true;
      $this.text('stop'); 
        }
                
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="myButton">Play</button>