A problem in Changeable Themes with JavaScript

Issue

I tried to test myself in JavaScript so I decided to make changeable themes website in codepen with JavaScript this is my code:enter image description here

but it didn’t work. please help me with it.

Solution

While @LoaiMasri was on a good track to solve the issue, there is still great way of improvement. Espacially to make the code shorter and more efficient if you have more themes to add.

First change you should consider over LoaiMasri‘s solution is to use a switch-statement over listing tons of if/else-statements.

However that will be to complicated for more then just a handfull of themes. The most efficient way is to add the themes through CSS. For that you do LoaiMasri‘s approach of using the value-attribute on the option tag. However give it a more direct value like theme-1, theme-2

Then you use the script below:

document.getElementById('Themes').addEventListener('change', function() {
  document.body.className = "";
  let theme = document.getElementById("Themes").value;
  document.body.classList.add(theme);
});

document.body.className = ""; -> This will remove all classes from the body-tag and works as a reset.

let theme = document.getElementById("Themes").value; -> That gets the value from the option-tag.

document.body.classList.add(theme); -> This will add now a class to the body-tag that equals the value of the option-tag.

All you now have to is to add classes to your CSS that equal the value of the option-tag. This will now solve the issue with 5 lines of JS code no matter how many themes you want to add (which is already smaller then LoaiMasri‘s solution).

document.getElementById('Themes').addEventListener('change', function() {
  document.body.className = "";
  let theme = document.getElementById("Themes").value;
  document.body.classList.add(theme);
});
.theme-1 {
  background-color: white;
  color: black;
}

.theme-2 {
  background-color: black;
  color: white;
}


.theme-3 {
  background-color: darkgray;
  color: white;
}
<select id="Themes">
  <option value="theme-1">White</option>
  <option value="theme-2">Black</option>
  <option value="theme-3">Dark</option>
</select>

Answered By – tacoshy

Answer Checked By – Terry (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.