Sometimes, we want to toggle audio play pause with a button or link with JavaScript.
In this article, we’ll look at how to toggle audio play pause with a button or link with JavaScript.
How to toggle audio play pause with a button or link with JavaScript?
To toggle audio play pause with a button or link with JavaScript, we can use a flag to keep track of when the audio is playing or paused.
For instance, we write:
<audio controls src="https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3"></audio>
<button>toggle</button>
to add an audio and button element.
Then we write:
const audio = document.querySelector('audio')
const button = document.querySelector('button')
let isPlaying = false;
button.onclick = () => {
isPlaying ? audio.pause() : audio.play();
};
audio.onplaying = () => {
isPlaying = true;
};
audio.onpause = () => {
isPlaying = false;
};
to select the audio and button elements with querySelector
.
Then we set button.onclick
to a click event handler function that checks if isPlaying
is true
or false
.
If it’s true
, then we pause the audio with audio.pause
.
Otherwise, we play the audio with audio.play
.
Then we set audio.onplaying
and audio.onpause
to functions that sets isPlaying
to true
and false
respectively.
Conclusion
To toggle audio play pause with a button or link with JavaScript, we can use a flag to keep track of when the audio is playing or paused.