darkmode.js.md
May 24, 2021 ยท View on GitHub
Table of Contents
- DarkMode
- darkmode
DarkMode
bootstrap-dark-5 darkmode.js -- the JavaScript module.
class DarkMode
Use this JS file, and its darkmode object, in your HTML to automatically capture prefers-color-scheme media query
events and also initialize tags with the data-bs-color-scheme attribute, or the document root (<HTML> tag) with the
user preferred color scheme.
The darkmode object can also be used to drive a dark mode toggle event, with optional persistance
storage in either a cookie (if GDPR consent is given) or the browsers localStorage object.
The module can be loaded into a html page using a standard script command.
<script src="darkmode.js"></script>
This will create a variable darkmode that is an instance of the DarkMode class.
Once the DOM is loaded the script will then look for any html tag with a data-bs-color-scheme attribute, and, if found
will use these tags to populate the current mode. If this data attribute is not found then the script will use the document
root (<HTML> tag) with the class dark or light.
For example, the bootstrap-blackbox.css variant requires the <HTML> to be initialized:
<!doctype html>
<html lang="en" data-bs-color-scheme>
<head>
<!-- ... -->
You can also pre-initialize the mode by populating the data attribute:
<html lang="en" data-bs-color-scheme="dark">
inDarkMode
property
Used to get the current state, true when in dark mode, false when in light mode or when mode not set
Can also be used to set the current mode (with no persistance saving)
Type: boolean
Examples
Get if page is in "Dark" mode
var myVal = darkmode.inDarkMode;
Set the page to the "Dark" mode
darkmode.inDarkMode = true;
hasGDPRConsent
Variable to store GDPR Consent. This setting drives the persistance mechanism.
Used in #saveValue to determine if a cookie or the localStorage object should be used.
- Set to
truewhen GDPR Consent has been given to enable storage to cookie (useful in Server-Side knowledge of user preference) - The setter takes care of swapping the cookie and localStorage if appropriate
- Default is
false, thus storage will use the browsers localStorage object (Note: No expiry is set)
Examples
Set once GDPR consent is given by the user
darkmode.hasGDPRConsent = true;
cookieExpiry
Expiry time in days when saving and GDPR consent is give
documentRoot
Saves the instance of the documentRoot (i.e. <html> tag) when the object is created.
Type: HTMLHtmlElement
Returns HTMLHtmlElement
readValue
Retrieves the color-scheme last saved
NOTE: is dependant on #hasGDPRConsent
Parameters
namestring -- Name of the cookie or localStorage->name
Returns string -- The saved value, either light or dark, or an empty string if not saved prior
eraseValue
Deletes the saved color-scheme
NOTE: is dependant on #hasGDPRConsent
Parameters
namestring
Returns void -- Nothing, erasure is assumed
getSavedColorScheme
Queries the <HTML> tag for the current color-scheme
(This value is set prior via the #setDarkMode) function.)
Returns string -- The current value, either light or dark, or an empty string if not saved prior
getPreferedColorScheme
Queries the prefers-color-scheme media query for the current color-scheme
(This value is set prior via the #setDarkMode) function.)
Returns string -- The current value, either light or dark, or an empty string if the media query is not supported
setDarkMode
Sets the color-scheme in the <HTML> tag as a class called either light or dark
Note: This function will modify your document root element, i.e. the <HTML> tag
Default behavior when setting dark mode true
<html lang="en" class="other-classes dark">
<!-- Note: the "light" class is removed -->
Default behavior when setting dark mode false
<html lang="en" class="other-classes light">
<!-- Note: the "dark" class is removed -->
Behavior when setting dark mode true, and dataSelector = "data-bs-color-scheme"
<html lang="en" data-bs-color-scheme="dark">
Behavior when setting dark mode false, and dataSelector = "data-bs-color-scheme"
<html lang="en" data-bs-color-scheme="light">
Parameters
darkModeboolean --truefor "dark",falsefor 'light'doSaveboolean -- Iftrue, then will also call #saveValue to save that state (optional, defaulttrue)
Examples
Set the color scheme to dark, saving the state to the persistance mechanism
document.querySelector("#darkmode-on-button").onclick = function(e){
darkmode.setDarkMode(true); // save=true is default
}
Set the color scheme to light, but not saving the state
document.querySelector("#darkmode-off-button-no-save").onclick = function(e){
darkmode.setDarkMode(false, false);
}
Returns void -- Nothing, assumes saved
toggleDarkMode
Toggles the color scheme in the <HTML> tag as a class called either light or dark
based on the inverse of it's prior state.
When #dataSelector is set, this is set in the given data selector as the data value.
(See #setDarkMode)
Parameters
doSave(optional, defaulttrue)
Examples
Bind an UI Element click event to toggle dark mode
document.querySelector("#darkmode-button").onclick = function(e){
darkmode.toggleDarkMode();
}
Returns void Nothing, assumes success
resetDarkMode
Clears the persistance state of the module and resets the document to the default mode.
Calls #eraseValue to erase any saved value, and then
calls #getPreferedColorScheme to retrieve the prefers-color-scheme media query,
passing its value to #setDarkMode to reset the users preference.
Examples
Bind a reset UI Element click event to reset the dark mode
document.querySelector("#darkmode-forget").onclick = function(e){
darkmode.resetDarkMode();
}
Returns void Nothing, no error handling is performed.
DATA_KEY
const -- Name of the cookie or localStorage->name when saving
VALUE_LIGHT
const -- String used to identify light mode (do not change), @see https://www.w3.org/TR/mediaqueries-5/#prefers-color-scheme
VALUE_DARK
const -- String used to identify dark mode (do not change), @see https://www.w3.org/TR/mediaqueries-5/#prefers-color-scheme
CLASS_NAME_LIGHT
const -- String used to identify light mode as a class in the <HTML> tag
CLASS_NAME_DARK
const -- String used to identify dark mode as a class in the <HTML> tag
getColorScheme
Gets the current color-scheme from the document <HTML> tag
Returns string -- The current value, either light or dark, or an empty string if not present
updatePreferedColorSchemeEvent
static -- function called by the media query on change event.
First retrieves any persistent/saved value, and if present ignores the event, but if not set then triggers the #setDarkMode function to change the current mode.
Returns void -- Nothing, assumes success
onDOMContentLoaded
static -- function called when the DOM finishes loading.
Does all the DarkMode initialization, including:
- Loading any prior stored preference (GDPR consent is not assumed)
- else, honoring any
<HTML>tagclass="dark|light"that Server-Side may set - else, honoring the browser / OS
prefers-color-schemepreference
and setting the derived mode by calling #setDarkMode
Followed by setting up the media query on change event
Warning: This function is automatically called when loading this module.
Returns void
darkmode
const -- This is the global instance (object) of the DarkMode class.