Dynamically changing website themes using jQuery

Loading

Dynamically Changing Website Themes Using jQuery

Introduction

Website themes play a crucial role in user experience. Giving users the ability to dynamically switch between different themes—such as light mode, dark mode, or custom color themes—enhances accessibility, personalization, and usability.

With jQuery, we can build an interactive theme-switching system that allows users to change themes dynamically without reloading the page. Additionally, we will store user preferences in localStorage, ensuring that the selected theme remains active even after refreshing the browser.


Table of Contents

  1. Understanding Theme Switching Mechanism
  2. Setting Up the Basic HTML Structure
  3. Creating CSS for Multiple Themes
  4. Implementing jQuery for Dynamic Theme Switching
  5. Saving and Retrieving User Preferences using localStorage
  6. Adding Smooth Theme Transition Effects
  7. Enhancing the Theme Switcher with Icons and Buttons
  8. Optimizing Performance and Accessibility
  9. Final Thoughts and Future Improvements

1. Understanding Theme Switching Mechanism

The idea behind dynamic theme switching is simple:

  1. Define multiple themes using CSS classes.
  2. Use jQuery to apply the selected theme dynamically.
  3. Store the user’s choice in localStorage so that it persists across sessions.

A theme switcher button will be created to allow users to switch between themes (e.g., Light Mode, Dark Mode, and Custom Mode).


2. Setting Up the Basic HTML Structure

First, create a simple HTML file with a button to toggle themes.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Theme Switcher</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>Dynamic Theme Switcher</h1>
        <p>Click the buttons below to change the website theme.</p>
        <button id="light-mode">Light Mode</button>
        <button id="dark-mode">Dark Mode</button>
        <button id="custom-mode">Custom Mode</button>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="script.js"></script>
</body>
</html>

Explanation

  • A <div class="container"> wraps the content to apply different theme styles.
  • Three buttons (Light Mode, Dark Mode, Custom Mode) will trigger theme changes.
  • jQuery will handle the theme-switching logic.

3. Creating CSS for Multiple Themes

Now, define three different themes using CSS.

styles.css

/* Default (Light Theme) */
body {
    font-family: Arial, sans-serif;
    background-color: #ffffff;
    color: #000000;
    text-align: center;
    padding: 20px;
    transition: all 0.5s ease-in-out;
}

.container {
    padding: 20px;
    border-radius: 10px;
}

/* Dark Mode */
.dark-theme {
    background-color: #1e1e1e;
    color: #ffffff;
}

/* Custom Mode (e.g., Blue Theme) */
.custom-theme {
    background-color: #004080;
    color: #ffcc00;
}

/* Buttons */
button {
    margin: 10px;
    padding: 10px 20px;
    font-size: 16px;
    border: none;
    cursor: pointer;
    border-radius: 5px;
}

#light-mode {
    background-color: #f0f0f0;
    color: #000;
}

#dark-mode {
    background-color: #333;
    color: #fff;
}

#custom-mode {
    background-color: #0080ff;
    color: #fff;
}

button:hover {
    opacity: 0.8;
}

Explanation

  • dark-theme class applies a dark background with white text.
  • custom-theme class applies a blue background with yellow text.
  • Smooth transitions (transition: all 0.5s ease-in-out;) ensure a better user experience.
  • Button styles differentiate theme switch options.

4. Implementing jQuery for Dynamic Theme Switching

Now, we will write jQuery to handle the theme-switching logic.

script.js

$(document).ready(function () {
    // Function to apply a theme
    function applyTheme(themeClass) {
        $("body").removeClass("dark-theme custom-theme").addClass(themeClass);
        localStorage.setItem("selectedTheme", themeClass); // Save to localStorage
    }

    // Event listeners for buttons
    $("#light-mode").click(function () {
        applyTheme(""); // No class for light mode
    });

    $("#dark-mode").click(function () {
        applyTheme("dark-theme");
    });

    $("#custom-mode").click(function () {
        applyTheme("custom-theme");
    });

    // Check localStorage for saved theme
    var savedTheme = localStorage.getItem("selectedTheme");
    if (savedTheme) {
        $("body").addClass(savedTheme);
    }
});

Explanation

  • The applyTheme() function removes existing theme classes and applies the selected one.
  • Click events trigger theme changes.
  • The selected theme is saved in localStorage, so it persists after page refresh.

5. Saving and Retrieving User Preferences with localStorage

Why use localStorage?

  • Ensures persistent user preferences.
  • Avoids the need for cookies or database storage.

How It Works in Our Code

  1. Saving Theme: localStorage.setItem("selectedTheme", themeClass);
  2. Retrieving Theme: var savedTheme = localStorage.getItem("selectedTheme");
  3. Applying Theme on Page Load:
if (savedTheme) {
    $("body").addClass(savedTheme);
}

🔹 This ensures users don’t have to reselect the theme after reloading the page.


6. Adding Smooth Theme Transition Effects

To make the theme switch more visually appealing, add fade-in effects using jQuery.

Enhancing script.js

function applyTheme(themeClass) {
    $("body").fadeOut(300, function () {
        $(this).removeClass("dark-theme custom-theme").addClass(themeClass).fadeIn(300);
    });
    localStorage.setItem("selectedTheme", themeClass);
}

Explanation

  • fadeOut(300) smoothly hides content.
  • fadeIn(300) restores the content after the new theme is applied.

7. Enhancing Theme Switcher with Icons and Buttons

To make the theme switcher more user-friendly, we can replace text buttons with icons.

Example (Font Awesome Icons)

<button id="light-mode"><i class="fas fa-sun"></i></button>
<button id="dark-mode"><i class="fas fa-moon"></i></button>
<button id="custom-mode"><i class="fas fa-palette"></i></button>

<!-- Include Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

🔹 This adds an aesthetic improvement with modern icons.


8. Optimizing Performance and Accessibility

  • Minimize jQuery animations to avoid performance issues.
  • Ensure high contrast colors for accessibility.
  • Allow users to reset the theme with an additional button.
<button id="reset-theme">Reset Theme</button>
$("#reset-theme").click(function () {
    $("body").removeClass("dark-theme custom-theme");
    localStorage.removeItem("selectedTheme");
});

Conclusion

We built a dynamic theme switcher using CSS, jQuery, and localStorage.
The theme persists after page reloads.
We added smooth transitions for a better user experience.
Icons improve aesthetics.

Now, you can expand this by adding more themes, a color picker, or animations for a richer user experience!

Leave a Reply

Your email address will not be published. Required fields are marked *