1

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!

ZoEM
  • 850
  • 9
  • 27

1 Answers1

4

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>
Cyril Iselin
  • 596
  • 4
  • 20
  • That's what I wanted! Although I wanted the text on the buttons change too, to either Sound off or Sound on depending on what's clicked, any idea what I should do there? – ZoEM May 15 '16 at 17:46
  • Works exactly the way I wanted to, thank you for your help – ZoEM May 15 '16 at 18:21