So, I have an audio track autoplay when opening the website

<audio class="topper" autoplay loop id="minuscolo">
    <source src="media/minuscolo.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
</audio>

and I have an image that I would like to use to control the music

<img class="hvr-shrink square" alt="Pause" src="media/gogh.png" onclick="document.getElementById('minuscolo').pause()">

I can assign a play or pause function to it, but I can't find a way to use both functions on the same image so that if music is playing it acts as a pause button and if there's no music playing it acts as a play button.

1

There are 1 answers

0
Alvaro Montoro On BEST ANSWER

You can achieve what you want by reading the paused property. It will return true if the audio is paused, or false if it's not. Then apply the .play() or .pause() methods accordingly.

To do this, just use a simple if ... else structure (pseudocode):

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

Or to make it shorter you could use the conditional ternary operator (? :) like this (pseudocode):

audio.paused ? audio.play() : audio.pause()

That applied to your code would look like this (changed the image and audio for the demo):

<audio class="topper" autoplay loop id="minuscolo">
    <source src="http://www.html5tutorial.info/media/vincent.mp3" type="audio/mpeg"/>
    Your browser does not support the audio element.
</audio>

<img class="hvr-shrink square" alt="Pause" src="http://lorempixel.com/g/100/100/abstract/" onclick="document.getElementById('minuscolo').paused ? document.getElementById('minuscolo').play() : document.getElementById('minuscolo').pause()">

You can also see it on this JSFiddle.

Having everything online is a bit ugly. It would be nicer if you attached a click event on the element that called a function, and then have the JavaScript logic separated from the HTML code. Like it is explained on this W3C wiki link.