Create a mute button with JavaScript

By 01/14/2016Coding

When we first had to create a mute button, I found it a little complicated. Now that I managed to do it, I see that it is actually quite logical. Thus I want to save others (and future me) from the frustrations I went through. Therefore I present to you… The jQuery code needed to create a mute button!

Code for a Mute Button

$(document).on(“ready”, titel);

function titel() {
$(“.mutebutton”).on(“click”, mutebuttonclick);
setTimeout(katind, 6000);

function mutebuttonclick() {
if ($(“#stjerne”)[0].muted == true) {
$(“#stjerne”)[0].muted = false;
$(“#blop”)[0].muted = false;
$(“#slap”)[0].muted = false;
$(“#soundtrack”)[0].muted = false;

else {
$(“#stjerne”)[0].muted = true;
$(“#blop”)[0].muted = true;
$(“#slap”)[0].muted = true;
$(“#soundtrack”)[0].muted = true;

When you click on the mutebutton this jQuery code will make the following command: IF it is true that the sound in the audio tag with the id Stjerne is muted, then none of the sounds should be muted anymore. Otherwise all of the sounds should be muted.

Of course you have to update it before you can use it. What you want to happend on your site when it is ready is up to you. The important thing is that the mutebutton is activated in the first function, which is done with this command: $(“.mutebutton”).on(“click”, mutebuttonclick);

Another important thing to mention is that you have to create a button in your HTML-document with the titel mute (or the like) and with the class mutebutton.

And then as a last and really important thing, you have to update the id names in the code, to make it match the id’s you have given your audio tags. If you have more sounds in your HTML-document, you can just add more of these lines $(“#[AUDIO TAG ID]”)[0].muted = true;. Just remember to add them both in the if {} and the else {} part of the code.

Leave a Reply