I’m trying to make a bunch of toggle mute buttons. To prevent myself from writing a bunch of functions that all do the same thing I use parameters, and I think that is where the code messes up. To my knowledge this is supposed to work if I weren’t using parameters.
let isMuted1 = false,
isMuted2 = false,
isMuted3 = false,
isMuted4 = false,
isMuted5 = false,
isMuted6 = false,
isMuted7 = false;
muteButton1.addEventListener('click', () => {
muteMonster(monster1, audio1, isMuted1);
})
muteButton2.addEventListener('click', () => {
muteMonster(monster2, audio2, isMuted2);
})
muteButton3.addEventListener('click', () => {
muteMonster(monster3, audio3, isMuted3);
})
muteButton4.addEventListener('click', () => {
muteMonster(monster4, audio4, isMuted4);
})
muteButton5.addEventListener('click', () => {
muteMonster(monster5, audio5, isMuted5);
})
muteButton6.addEventListener('click', () => {
muteMonster(monster6, audio6, isMuted6);
})
muteButton7.addEventListener('click', () => {
muteMonster(monster7, audio7, isMuted7);
})
function muteMonster(monster, audioElement, isMuted) {
if (!isMuted) {
isMuted = true;
monster.style.opacity = "0.5";
audioElement.muted = true;
} else {
isMuted = false;
monster.style.opacity = "1";
audioElement.muted = false;
}
}
I tried making the toggle button by flicking a bool to false if it was true, and to true if it was false. Executing different code depending on the state of the bool. I had to do this for a bunch of buttons so I wrote only one function that takes in a different bool depending on what button you press.
(Also I’m sure there’s a neater way to do what I’m trying to do but I’m a little pressed on time and wouldn’t know how yet)
2
Answers
You can move
isMuted
,monster
andaudio
variables into DOM’s attribute. So the button will keep its state (on/off), and the name of a corresponding monster and audio.Create maps of monsters and audios where name of attribute corresponds to the variable. Then call
setButtonAttributes
to set names of audios and monsters as button attributes.It is important that in
buttons
array you keep DOM objects, you can get them with methods likedocument.getElementById("BUTTON_ID")
,document.getElementsByTagName("button)
, etc.Here is a way to populate your Arrays with the correct values (all = true at start) for your boolean Array, the references in monsters Array…
The last function
function resetToTrue(index)
update the boolean Array and avoid to have more than one monster not muted.TAKE CARE : Click on "Full page" when you run the snippet if you do not want to see the logs over your buttons, they will not be clickable otherwise!
Have a nice day.
If multiple monsters may be "un-muted" , just comment those lines in the function
resetToTrue()
like this :