0

Clicking anywhere on the site plays a mouse-click sound. This could be annoying so I added a button that will disable and re-enable the sound on click. I can disable the sound, but not re-enable For some reason, the variable soundDisabled isn't changing to true on click. None of the questions that came up when I googled seemed to help my case.

Jsfiddle

let soundDisabled = false;
let soundControl = document.getElementById("control");

function clickSound() {
  var audio = new Audio('https://files.catbox.moe/z1ss03.mp3');
  audio.volume = 0.5;
  audio.play();
}
window.addEventListener('click', clickSound, false);


soundControl.onclick = function() {
  if (soundDisabled === false) {
    window.removeEventListener('click', clickSound, false);
    soundControl.innerHTML = "sound off";
    soundDisabled === true;
  } else {
    window.addEventListener('click', clickSound, false);
    soundControl.innerHTML = "sound on";
  }
}
<button id="control">click here</button>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Girl
  • 1
  • 2
  • 3
    it's not an assingment here: `soundDisabled === true;` use `soundDisabled = true;` instead. – Nina Scholz Mar 20 '23 at 07:49
  • So much simpler and using less resources too: `let soundEnabled = true; const audio = new Audio('https://files.catbox.moe/z1ss03.mp3'); audio.volume = 0.5; window.addEventListener('click', () => { if (soundEnabled) audio.play(); }); document.getElementById("control").addEventListener("click", function(e) { soundEnabled = !soundEnabled; this.textContent = soundEnabled ? "sound off" : "sound on"; })` – mplungjan Mar 20 '23 at 07:59

0 Answers0