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.
You can achieve what you want by reading the
paused
property. It will returntrue
if the audio is paused, orfalse
if it's not. Then apply the.play()
or.pause()
methods accordingly.To do this, just use a simple
if ... else
structure (pseudocode):Or to make it shorter you could use the conditional ternary operator (
? :
) like this (pseudocode):That applied to your code would look like this (changed the image and audio for the demo):
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.