Before typing your JavaScript:
You can use CSS to make a @media
query that says to have an ::after
pseudo class on the body
element that has a different text depending on the color-scheme of the user. In order to make sure the ::after
on the body
element doesn't confuse users, add a display: none;
on the after element.
CSS Code:
@media (prefers-color-scheme:dark){
body::after{
content: 'd';
display: none;
}
}
@media (prefers-color-scheme:light){
body::after{
content: 'l';
display: none;
}
}
Now for your JavaScript:
Since we have an object in the document to select, we can get the ::after
pseudo class of the body
element. We need to get the content of it, just make sure your CSS loads before your JavaScript does! 'd'
for dark mode, and 'l'
for light mode.
JavaScript Code:
var colorScheme = getComputedStyle(document.body,':after').content;
// d for dark mode, l for light mode.
Why this could be useful
You can do this in CSS and HTML, but why would you do it in JavaScript?
You would use JavaScript because you might have to add an img
element, but the image has text, so you got 2 images, one for light mode, the other for dark mode. So, you could use JavaScript to change the src
attribute's value of the img
element to the correct URL based off of the color-scheme.
There is probably more uses, but that is the use I can think of.
Sources:
I learned getComputedStyle
function from this stackoverflow article.
I learned @media (prefers-color-scheme:
color scheme to detect)
from MDN Web Docs.
I learned how to get .content
of computed style from seeing it as a code suggestion on VSCode as I typed getComputedStyle(document.body,':after')
and it working as I expected it to. (If I saw it on an article, I can't find which I visited)