How to switch between Dark Mode and Light Mode based on cookie in Javascript

Created at 13-Feb-2024 , By samar

In this article we will learn about how to change the theme option from dark to light mode and light to dark mode basic of user preferences by using cookie data.

As technology evolves, so do our preferences and expectations when it comes to interacting with websites. One such trend that has gained significant traction in recent years is the adoption of dark mode—a feature beloved by many for its sleek appearance and reduced eye strain.

Here is step by step instructions how can we change the mode of website between dark to light or light to dark on the basic of cookie data.

1. Create HTML Documents

First create two HTML files named about.html and contact.html in your project directory.

Place below code in about.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>About</title>
    
    <style>
        body.dark {
            background-color: #202020;
            color: #ffffff;
        }
        body.light {
            background-color: #ffffff;
            color: #202020;
        }
    </style>
</head>
<body class="light">
    <button onClick="changeTheme()"> update theme </button>
    <h2> About Page </h2>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus libero suscipit odit alias adipisci veritatis, consequuntur, ipsam illo commodi delectus ipsa laudantium, inventore aspernatur assumenda saepe ipsum incidunt expedita? Accusantium.</p>
    <a href="./contact.html"> Contact Page</a>
    <script src="./script.js"></script>
</body>
</html>

Now place below code in contact.html file.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact </title>
    
    <style>
        body.dark {
            background-color: #202020;
            color: #ffffff;
        }
        body.light {
            background-color: #ffffff;
            color: #202020;
        }
    </style>
</head>
<body class="light">
    <button onClick="changeTheme()"> update theme </button>

    <h2>Contact Page</h2>

    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus libero suscipit odit alias adipisci veritatis, consequuntur, ipsam illo commodi delectus ipsa laudantium, inventore aspernatur assumenda saepe ipsum incidunt expedita? Accusantium.</p>

    <a href="./about.html"> About Page</a>

    <script src="./script.js"></script>
</body>
</html>

Now create script.js file in same project directory and paste bleow code.


function changeTheme() {
    var theme = getCookie('theme');
    if(theme == 'light') {
        document.cookie = "theme=dark;Wed, 05 Aug 2024 23:00:00 UTC";
    }else {
        document.cookie = "theme=light;Wed, 05 Aug 2024 23:00:00 UTC";
    }
    currentTheme = (theme == 'light') ? 'dark' : 'light';
    applyTheme(currentTheme);
}

function getCookie(cookieName) {
    let cookie = {};
    document.cookie.split(';').forEach(function(el) {
        let [key,value] = el.split('=');
        cookie[key.trim()] = value;
    })
    return cookie[cookieName];
}

function applyTheme(theme) {
    document.body.className = "";
    document.body.classList.add(theme);
}
function readThemeFromCookie() {
    var theme = document.cookie.replace(/(?:(?:^|.*;\s*)theme\s*\=\s*([^;]*).*$)|^.*$/, "$1");
    var theme = theme || 'light';
    if (theme) {
        applyTheme(theme);
    }
}

readThemeFromCookie();

Your cookie name (theme) and value should be (light or dark) as below.

Name    Value   Domain      Path                            
theme   light   localhost   /learning/php/cookie-session	

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.