Before you start coding in JavaScript:
Utilize CSS to create a @media
query that instructs an ::after
pseudo class on the body
element to display different text based on the user's color scheme preference. To prevent confusion for users, ensure to add a display: none;
property to the ::after
element inside the body
.
CSS Snippet:
@media (prefers-color-scheme:dark){
body::after{
content: 'd';
display: none;
}
}
@media (prefers-color-scheme:light){
body::after{
content: 'l';
display: none;
}
}
Next step is adding your JavaScript code:
Given that we have a target object within the document to select, we can access the ::after
pseudo class of the body
element. Extracting the content from it is crucial, ensuring your CSS loads before executing any JavaScript commands! Remember, use 'd'
for dark mode and 'l'
for light mode.
JavaScript Piece:
var colorScheme = getComputedStyle(document.body,':after').content;
// d for dark mode, l for light mode.
The significance of this approach:
Although achievable through CSS and HTML alone, a scenario may arise where employing JavaScript becomes necessary. For instance, when inserting an img
element containing text, requiring two images—one for light mode, the other for dark mode. Here, JavaScript proves handy in dynamically adjusting the src
attribute value of the img
element based on the active color scheme.
While there are possibly more applications, this specific use case stands out as a practical example.
References:
I gleaned insights on using the getComputedStyle
function from a helpful discussion on Stack Overflow.
My understanding of @media (prefers-color-scheme:
color scheme definition)
was refined by consulting MDN Web Docs.
Additionally, I acquired knowledge on extracting .content
from computed styles through a code suggestion in VSCode while typing
getComputedStyle(document.body,':after')
, validating its functionality and utility. (Unfortunately, the original source of this information is untraceable.)