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.
CodePudding user response:
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>
CodePudding user response:
document.getElementById("Themes").addEventListener("change", function () {
document.body.style.backgroundColor = this.value;
});
this is a answer but I recommended to add values as a number
like this code
<select id="Themes">
<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Dark</option>
</select>
document.getElementById("Themes").addEventListener("change", function () {
let theme = document.getElementById("Themes").value;
if (theme == 1) {
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
} else if (theme == 2) {
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
} else if (theme == 3) {
document.body.style.backgroundColor = "darkgrey";
document.body.style.color = "white";
}
});