Example Description
In this example, site visitors can switch between a default color scheme and “dark mode,” known for improving readability and reducing eye fatigue. The site visitor’s preferred mode is maintained across all pages of the site and from one browsing session to the next.
How We Built It
Page Elements
On each page in our site we added the following elements:
-
Switch input: To toggle between the default mode and dark mode. Make sure the switch’s ID is the same on each page.
-
Container box: Holds all the elements on the page. Box.style.backgroundColor changes when dark mode is enabled.
-
Custom menu: (Only on Home page) Built from several buttons with a transparent background. Button.style.color (text color) changes when dark mode is enabled.
-
Text elements: Several text elements for title, description, footer, etc. Text.html changes color when dark mode is enabled.
Code
Then we added the following code to the site tab so it will run for every page in the site:
-
Import functionality for working with local storage. Local storage allows us to “remember” the visitor’s mode choice when navigating to a different page and between browsing sessions.
-
Define global objects to store page elements defined by type, dark mode color styles, and default color styles. Default styles are extracted from the page elements when the page loads.
-
When the page loads, do the following:
-
Select text, boxes, and buttons by type and save their default styles.
-
Check local storage to see if dark mode was enabled in the most recent browser session. If so, enable dark mode and turn on the switch. If not, enable default mode and turn off the switch.
-
Use an onChange event handler to switch from the current mode to the other mode anytime the switch is toggled.
-
-
Function for switching to default mode:
Note that we use template literals for handling variables and expressions in strings.-
Tag dark mode as disabled in both our global variable and local storage.
-
For each text element, box, and button, replace the current style with the default mode styles.
-
-
Function for switching to dark mode:
-
Tag dark mode as enabled in both our global variable and local storage.
-
For text elements, we use a regular expression cleaner to help us insert a new HTML tag for the dark mode text color. The regex cleaner extracts the plain text from inside the HTML tags. In the Text.html property, we replace the plain text with plain text + dark mode HTML tag.
-
For each box and button, replace the current style with the dark mode style.
-
Related Examples
Did this help?
|
Thanks for your feedback!
Gift Quiz
Help customers find the perfect gift with a quiz and product recommendations.
Intermediate
Image Fit Mode
Experiment with different ways to fit your image in an image element
Beginner
Tabs
Create tabs using a multi-state box
Beginner