How to create a dark mode toggle in Breakdance

The CSS prefers-color-scheme media query is utilized to identify a user's color scheme preference, allowing for automatic switching between light and dark modes. Additionally, user preferences can be retained using local storage or session storage. This ensures that returning visitors always encounter their preferred viewing experience.

Step 1

Add a Code Block and paste this code in the PHP panel:

<script src="https://cdn.jsdelivr.net/npm/darkify-js@2.8.2023"></script>

Or simply save the JS file , upload it in your website and load it locally with your favorite Snippet Manager (if you don't want to use a CDN).

Step 2

We need to know what colors to change. By chance, Breakdance set the global colors in variables, so we just have to use the same variables but with different colors (for the Dark mode).

We have 7 variables (don't forget that the Brand and Links colors also have an hover state) :

bd-global-colors
bd-global-colors-hover

Using the same variables, we define our dark theme (the variable names are self-explanatory). Here are the new colors we want to have in dark mode. Paste the code, with your own colors, in the Code Block or in the CSS Stylesheet in the Global Settings:

:root:is([data-theme='dark']) {
--bde-brand-primary-color: purple;
--bde-brand-primary-color-hover:yellow;
--bde-body-text-color: #ccc;
--bde-headings-color:#fff;
--bde-links-color: darkorange;
--bde-links-color-hover:purple;
--bde-background-color : black;
}

Step 3

Still in the same code Block, in the Javascript panel, we can add the final code:

const options = {
useLocalStorage: true,
useSessionStorage: false,
autoMatchTheme: true,
}

var darkMode = new Darkify('#darkModeToggle',options)

As we can see, there are 3 options :

  • useLocalStorage : The toggle settings will be saved locally but still remains until it is explicitly deleted.

  • useSessionStorage : only remains for the duration of the page session. It gets cleared as soon as the user closes the specific browser tab

  • autoMatchTheme : It uses the CSS prefers-color-scheme media query to check the user’s color scheme preference and automatically toggle between light and dark modes.

The Code Block should looks like this:

darkmode-codeblock

Step 4

Finally, add a Button (or a link, or any element you want, that will be used as a toggle) and add the ID #darkModeToggle:

darkmode-button-id

More info about darkify-js : https://github.com/emrocode/darkify-js

Do you want some cool toggles?

Take a look at these cools Dark Mode toggles available in AssetsForWP.

Darkmode Toggles from AssetsForWordPress website