Dark Mode Code Explanation for Wix Studio


Dark Mode Code Explanation for Wix Studio

This code enables the implementation of a dark mode on a Wix Studio site using local storage to save user preferences. It should be added to the master section of the Wix Studio site to ensure dark mode functionality across all pages.

Importing Required Modules

import { local } from 'wix-storage';

This line imports the local functionality from the wix-storage module, allowing the storage of data locally in the user’s browser.

Defining Page Elements

const pageElements = { 
    textElements: [],
    boxContainers: [],
    buttons: []
};

The pageElements object holds arrays of different types of page elements, including text elements, box containers, and buttons.

Defining Dark Mode Color Scheme

let darkMode = { 
    textElementFontColor: "black",
    boxContainersBackgroundColor: "#ffffff",
    buttonsColorDarkMode: "black",
    buttonsColorLightMode: "#FF7D19",
    labelColorDarkMode: "#000000",
    labelColorLightMode: "#ffffff"
};

The darkMode object defines the color scheme for dark mode and light mode, including text color, background color of containers, button colors, and label colors.

Storing Default Color Scheme

let defaultScheme = { 
    defaultTextElementsHtml: [],
    boxContainersBackgroundColor: [],
    buttonsColor: [],
    defaultLabelColor: "#ffffff"
};

The defaultScheme object stores the default color scheme of the site, so it can be restored when dark mode is turned off.

onReady Function

$w.onReady(function () {
    saveDefaultColorScheme(); 
    checkDarkMode(); 
    addEventListenerToDarkmodeSwitch(); 
});

When the site loads, this function saves the default color scheme, checks if dark mode is enabled, and adds an event listener to the dark mode switch.

Saving Default Color Scheme

function saveDefaultColorScheme() {
    pageElements.textElements = $w("Text");
    pageElements.boxContainers = $w("Box");
    pageElements.buttons = $w("Button");

The saveDefaultColorScheme function selects all text elements, box containers, and buttons on the page and stores their original color schemes.

    pageElements.textElements.forEach(textElement => {
        if (!textElement.id.startsWith("Not")) {
            defaultScheme.defaultTextElementsHtml.push(textElement.html);
        }
    });

For each text element, this code saves its original HTML (excluding elements with IDs starting with “Not”) in the defaultTextElementsHtml array.

    pageElements.boxContainers.forEach(boxContainer => {
        defaultScheme.boxContainersBackgroundColor.push(boxContainer.style.backgroundColor);
    });

For each box container, the code saves its original background color in the boxContainersBackgroundColor array.

    pageElements.buttons.forEach(button => {
        defaultScheme.buttonsColor.push(button.style.color);
    });
}

For each button, the code saves its original color in the buttonsColor array.

Checking Dark Mode Status

function checkDarkMode() {
    darkMode.enabled = JSON.parse(local.getItem('darkmodeEnabled'));
    if (darkMode.enabled === true) {
        switchToDarkMode();
        $w("#darkModeSwitch").checked = true;
        $w("#textModo").text = "Modo Light";
    } else {
        switchToDefault();
        $w("#darkModeSwitch").checked = false;
        $w("#textModo").text = "Modo Dark";
    }
}

The checkDarkMode function checks if dark mode is enabled by retrieving the value from local storage. If dark mode is enabled, it applies dark mode and updates the switch and text accordingly. Otherwise, it applies the default mode.

Adding Event Listener to Dark Mode Switch

function addEventListenerToDarkmodeSwitch() {
    $w("#darkModeSwitch").onChange((event) => {
        darkMode.enabled = !darkMode.enabled;
        if (darkMode.enabled) {
            switchToDarkMode();
            $w("#textModo").text = "Modo Light";
        } else {
            switchToDefault();
            $w("#textModo").text = "Modo Dark";
        }
    });
}

The addEventListenerToDarkmodeSwitch function adds an event listener to the dark mode switch. When the switch is toggled, it toggles the dark mode status and updates the switch and text accordingly.

Switching to Dark Mode

function switchToDarkMode() {
    local.setItem('darkmodeEnabled', true);

The switchToDarkMode function activates dark mode and saves this preference in local storage.

    const htmlTagCleanerRegex = /<[^>]*>?/gm;
    pageElements.textElements.forEach(textElement => {
        if (!textElement.id.startsWith("Not")) {
            let text = textElement.html.replace(htmlTagCleanerRegex, '');
            $w(`#${textElement.id}`).html = textElement.html.replace(text, `<span style="color:${darkMode.textElementFontColor}">${text}</span>`);
        }
    });

This code cleans HTML tags from text elements and applies the dark mode text color to the remaining text.

    pageElements.boxContainers.forEach(boxElement => {
        $w(`#${boxElement.id}`).style.backgroundColor = darkMode.boxContainersBackgroundColor;
    });

This code sets the background color of box containers to the dark mode background color.

    pageElements.buttons.forEach(buttonElement => {
        $w(`#${buttonElement.id}`).style.color = darkMode.buttonsColorDarkMode;
    });

This code sets the color of buttons to the dark mode button color.

    pageElements.buttons.forEach(buttonElement => {
        $w(`#${buttonElement.id}`).style.color = darkMode.labelColorDarkMode;
    });
}

This code sets the label color of buttons to the dark mode label color.

Switching to Default (Light Mode)

function switchToDefault() {
    local.setItem('darkmodeEnabled', false);

The switchToDefault function deactivates dark mode and restores the default color scheme, saving this preference in local storage.

    pageElements.textElements.forEach((textElement, index) => {
        if (!textElement.id.startsWith("Not")) {
            $w(`#${textElement.id}`).html = defaultScheme.defaultTextElementsHtml[index];
        }
    });

This code restores the original HTML of text elements.

    pageElements.boxContainers.forEach((boxElement, index) => {
        $w(`#${boxElement.id}`).style.backgroundColor = defaultScheme.boxContainersBackgroundColor[index];
    });

This code restores the original background color of box containers.

    pageElements.buttons.forEach((buttonElement, index) => {
        $w(`#${buttonElement.id}`).style.color = defaultScheme.buttonsColor[index];
    });

This code restores the original color of buttons.

    pageElements.buttons.forEach(buttonElement => {
        $w(`#${buttonElement.id}`).style.color = darkMode.labelColorLightMode;
    });
}

This code sets the label color of buttons to the light mode label color.


2 Likes

This is very thorough, great work :clap: