Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Issue with access a variables value outside of a function

let dark = true;
function toggle() {
    dark = false;
    document.body.classList.toggle('dark-mode');
}

if (dark = false) {
    document.getElementById("logo").src="../../img/Kevin D (White).png";
}else {
    document.getElementById("logo").src="../../img/Kevin D (Black).png";
}

Above is my code. Whenever I click the button the image does not go to the white version, instead it just stays black even on a black background, how would I fix this? The code is also attached to a button which would call that function

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There are a few things to solve here:

  • You need to call the if again when the variable changes, we do this by wrapping it in a function, then calling it on load and whenever the toggle is called.
  • Toggle currently doesn’t "toggle", set the value to !dark to invert it every time.
  • The if is currently assigning the value false to the dark variable, we need to compare it instead, and since it’s already a boolean, it can simply be if (dark) {}
var dark = true;

function toggle() {
  dark = !dark; // To actually toggle the variable you need to invert the current value
  document.body.classList.toggle('dark-mode');
  // After the variable is toggle, call the function to update the theme
  changeTheme()
}

function changeTheme() {
  if (dark) {
    console.log("It's dark!")
  } else {
    console.log("It's light!")
  }
}

// Cal the function on load to set the initial theme
changeTheme()

// Add an event listener to call the toggle function
document.getElementById("toggle").addEventListener("click", toggle);
<div id="toggle">Toggle</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading