So the way I want to do the toggling of light and dark themes is that every thing that changes will have an other class in css that it will change to.
Like this:
css:
.p-fooldal
{
color:black;
}
.p-fooldal-light-mode
{
color:white;
}
html:
<p class="p-fooldal"> asd asd </p>
JS is where I need help. I have done the some with the body, but I cant do the same, because I want different style for different paragraphs, what other way can I refer to a paragraph.
var body = document.body;
function toggleDark()
{
body.classList.toggle("body-light-mode");
}
I have tried bruteforcing myself whit this:
const pfooldal = document.classList.pfooldal;
function toggleDark()
{
pfooldal.classList.toggle("p-fooldal-light-mode")
}
I know its awful but it has to be something like that.
3
Answers
Rather than changing the classes of every element, only toggle the
body-dark-mode
class ondocument.body
. Then using CSS, define styles for descendants of.body-dark-mode
. This way, wheneverdocument.body
gets the class, every element that has a style defined will also be selected as its child and the alternative CSS will be applied. Like this:I would advise to use one class on the body and do the rest using CSS, like this:
The (||) is the or operator, so using it on the body allows you to add or remove classes based on the first class(dark-theme) or the second class (light-theme)
Then you can have a class on the body for dark mode:
body.dark-mode{ … }
and then add a button to your html for the user to switch from light or dark mode, and then use java script to add or remove dark-mode from the class list(aka toggle)
Personally when I implement dark/light modes for websites, I like to create a main.css file that has all the global styles that will apply to both modes. Then create a dark.css and a light.css for your changing colors.
So, for example:
main.css:
dark.css:
light.css:
In your html, you will declare your main.css file first and then whichever light mode you want to be the default. Be sure to include file paths if they aren’t all in the same folder.
index.html:
By declaring your light mode CSS file with an id, you can change it with javascript. Put the following line in your javascript file. You can nest it in a function called by a button or Event Listener and then have it toggle between light.css and dark.css
script.js:
By doing it this way instead of defining different classes for different elements, you can affect all of your elements with one function call.