Sometimes, we want to play a beep sound on button click with JavaScript.
In this article, we’ll look at how to play a beep sound on button click with JavaScript.
Play a Beep Sound on Button Click with JavaScript
To play a beep sound on button click with JavaScript, we can add an event listener to a button.
And in the event listener, we can call the play
method on the Audio
instance with the URL set to the beep sound clip.
For instance, we write:
<button>
foo
</button>
to add a button.
Then we write:
const audio = new Audio('https://www.soundjay.com/buttons/beep-01a.mp3')
const button = document.querySelector('button')
button.addEventListener('click', (e) => {
audio.play()
})
to create an Audio
instance with the beep sound URL and assign it to audio
.
Then we select the button with document.querySelector
.
And finally, we call button.addEventListener
with 'click'
to add a click event listener.
The 2nd argument is a callback that runs when we click the button.
In it, we call audio.play
to play the clip.
Therefore, when we click the button, the beep sound clip will play.
Conclusion
To play a beep sound on button click with JavaScript, we can add an event listener to a button.
And in the event listener, we can call the play
method on the Audio
instance with the URL set to the beep sound clip.