Categories
JavaScript Answers

How to mute all sound in a page with JavaScript?

Spread the love

Sometimes, we want to mute all sound in a page with JavaScript.

In this article, we’ll look at how to mute all sound in a page with JavaScript.

How to mute all sound in a page with JavaScript?

To mute all sound in a page with JavaScript, we can set the muted property of each audio element to true.

For instance, we write:

<audio src='https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3' controls></audio>
<audio src='https://file-examples-com.github.io/uploads/2017/11/file_example_MP3_700KB.mp3' controls></audio>

to add the audio elements.

Then we write:

const elems = document.querySelectorAll("video, audio");
for (const el of elems) {
  el.muted = true
  el.pause()
}

We select all the audio and video elements with querySelectorAll.

Then we loop through each element in elems and set the muted property of it to true to mute the audio.

We can also call pause to pause the audio.

Conclusion

To mute all sound in a page with JavaScript, we can set the muted property of each audio element to true.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *