I recently created a simplified version to showcase the usage of the background-color
property, which can also be applied to the text-color
.
Step 1:
Firstly, we must incorporate a unique onclick
trigger to the buttons/boxes. This trigger will activate a script upon being clicked.
Step 2:
We introduce a function that eliminates any existing classes responsible for the current background-color
. This is achieved using the following code snippet:
document.querySelector("body").classList.remove("class");
. Essentially, this removes any prior classes applied to the body tag.
Step 3:
To set the desired background color, the same JavaScript command is used but with add
instead of
remove</code. The line of code looks like this: <code>document.querySelector("body").classList.add("class");
.
Step 4:
Finally, we make adjustments in the CSS file corresponding to the specified class.
There are certainly ways to optimize and condense the script further. Nevertheless, I believe that this method is straightforward and easily reproducible, especially for beginners.
function textWhite() {
document.querySelector("body").classList.remove("background-blue"); document.querySelector("body").classList.remove("background-orange"); document.querySelector("body").classList.remove("background-green");
document.querySelector("body").classList.add("background-white");
}
function textBlue() {
document.querySelector("body").classList.remove("background-white"); document.querySelector("body").classList.remove("background-orange"); document.querySelector("body").classList.remove("background-green");
document.querySelector("body").classList.add("background-blue");
}
function textOrange() {
document.querySelector("body").classList.remove("background-blue"); document.querySelector("body").classList.remove("background-white"); document.querySelector("body").classList.remove("background-green");
document.querySelector("body").classList.add("background-orange");
}
function textGreen() {
document.querySelector("body").classList.remove("background-white"); document.querySelector("body").classList.remove("background-orange"); document.querySelector("body").classList.remove("background-blue");
document.querySelector("body").classList.add("background-green");
}
.background-white {
background-color: white;
}
.background-blue {
background-color: blue;
}
.background-orange {
background-color: orange;
}
.background-green {
background-color: green;
}
<body>
<h2>background colors</h2>
<div class="theme-options">
<div onclick="textWhite()" class="theme-white">White</div>
<div onclick="textBlue()" class="theme-blue">Blue</div>
<div onclick="textOrange()" class="theme-orange">Orange</div>
<div onclick="textGreen()" class="theme-green">Green</div>
</div>
<hr>
<h2>text Color</h2>
<div class="theme-options">
<div class="theme-white">White</div>
<div class="theme-blue">Blue</div>
<div class="theme-orange">Orange</div>
<div class="theme-green">Green</div>
</div>
</body>