Using jQuery to dynamically switch CSS themes

Loading

Using jQuery to Dynamically Switch CSS Themes

Introduction

As web development continues to evolve, providing users with a customizable interface has become a standard feature. One of the most requested features is theme switching, allowing users to toggle between different CSS themes such as light mode and dark mode.

jQuery, a powerful JavaScript library, provides an easy way to implement theme switching dynamically without reloading the page. By modifying CSS files, toggling classes, or manipulating inline styles, we can enable users to switch themes effortlessly. Additionally, we can store user preferences using LocalStorage, ensuring that the selected theme persists across page reloads.

This guide will explain in detail how to implement theme switching using jQuery, covering:
✔️ Changing CSS dynamically
✔️ Applying different stylesheets
✔️ Using LocalStorage for theme persistence
✔️ Enhancing user experience with smooth transitions


1. Understanding Theme Switching

What is Theme Switching?

Theme switching allows users to select a different visual appearance for a webpage. Common examples include:

  • Light Mode & Dark Mode: Switching background and text colors to match user preferences.
  • Custom User Themes: Allowing users to choose from multiple predefined themes.
  • Accessibility Themes: High contrast or dyslexia-friendly fonts for better readability.

How Theme Switching Works in jQuery

There are three primary approaches to switching themes:

  1. Changing the CSS file dynamically – Modifying the <link> tag to load a different stylesheet.
  2. Applying CSS classes – Toggling predefined CSS classes on the <body> or other elements.
  3. Modifying inline styles – Changing styles directly using jQuery.

Bonus: We will also save the user’s selected theme in LocalStorage to persist the settings even after page refresh.


2. Setting Up the Basic HTML Structure

Let’s start by creating a simple HTML layout with theme switching buttons.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Theme Switcher</title>
    <link id="themeStylesheet" rel="stylesheet" href="light-theme.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>Theme Switcher Example</h1>
        <button id="lightTheme">Light Theme</button>
        <button id="darkTheme">Dark Theme</button>
    </div>

    <script src="theme-switcher.js"></script>
</body>
</html>

Explanation:

  • We have two buttons (#lightTheme and #darkTheme) for switching themes.
  • The <link> element with id="themeStylesheet" will be modified dynamically using jQuery to switch stylesheets.
  • We include jQuery CDN to use jQuery functions.

3. Creating Theme Stylesheets

Now, let’s create two separate CSS files for the light and dark themes.

Light Theme (light-theme.css)

body {
    background-color: #ffffff;
    color: #333;
    font-family: Arial, sans-serif;
    text-align: center;
}
.container {
    padding: 20px;
}
button {
    padding: 10px;
    margin: 5px;
    cursor: pointer;
    border: none;
    background-color: #007bff;
    color: white;
}

Dark Theme (dark-theme.css)

body {
    background-color: #222;
    color: #ffffff;
    font-family: Arial, sans-serif;
    text-align: center;
}
button {
    padding: 10px;
    margin: 5px;
    cursor: pointer;
    border: none;
    background-color: #28a745;
    color: white;
}

Explanation:

  • Light Theme: White background with dark text.
  • Dark Theme: Dark background with white text.
  • Button styles change to match each theme.

4. Implementing Theme Switching with jQuery

Now, let’s write the jQuery script to switch themes dynamically.

theme-switcher.js

$(document).ready(function() {
    // Check if a theme is already stored in localStorage
    let storedTheme = localStorage.getItem("theme");

    if (storedTheme) {
        $("#themeStylesheet").attr("href", storedTheme);
    }

    // Light Theme Button Click Event
    $("#lightTheme").click(function() {
        $("#themeStylesheet").attr("href", "light-theme.css");
        localStorage.setItem("theme", "light-theme.css"); // Store preference
    });

    // Dark Theme Button Click Event
    $("#darkTheme").click(function() {
        $("#themeStylesheet").attr("href", "dark-theme.css");
        localStorage.setItem("theme", "dark-theme.css"); // Store preference
    });
});

How it Works:
✔️ When a button is clicked, the <link> element’s href attribute changes to switch stylesheets.
✔️ The selected theme is saved in localStorage, so it persists after a page refresh.
✔️ On page load, the script checks localStorage and applies the stored theme.


5. Adding Smooth Transitions for Better UX

To enhance user experience, let’s add a smooth transition effect.

Updated CSS for Transitions

body {
    transition: background-color 0.5s ease-in-out, color 0.5s ease-in-out;
}
button {
    transition: background-color 0.3s ease-in-out;
}

✔️ This makes the theme switch smoother instead of an instant change.


6. Adding More Themes Dynamically

If you want more than two themes, extend the script:

New Theme Stylesheets

Blue Theme (blue-theme.css)

body {
    background-color: #1e90ff;
    color: #fff;
}

Green Theme (green-theme.css)

body {
    background-color: #2e8b57;
    color: #fff;
}

Update HTML

<button id="blueTheme">Blue Theme</button>
<button id="greenTheme">Green Theme</button>

Update jQuery Script

$("#blueTheme").click(function() {
    $("#themeStylesheet").attr("href", "blue-theme.css");
    localStorage.setItem("theme", "blue-theme.css");
});

$("#greenTheme").click(function() {
    $("#themeStylesheet").attr("href", "green-theme.css");
    localStorage.setItem("theme", "green-theme.css");
});

✔️ Now users can choose from four different themes.


7. Using CSS Classes Instead of External Stylesheets

Instead of switching stylesheets, you can toggle classes on the <body> tag.

Simplified CSS

body.light-mode {
    background-color: white;
    color: black;
}

body.dark-mode {
    background-color: black;
    color: white;
}

Updated jQuery Code

$(document).ready(function() {
    let storedTheme = localStorage.getItem("theme");
    if (storedTheme) {
        $("body").addClass(storedTheme);
    }

    $("#lightTheme").click(function() {
        $("body").removeClass("dark-mode").addClass("light-mode");
        localStorage.setItem("theme", "light-mode");
    });

    $("#darkTheme").click(function() {
        $("body").removeClass("light-mode").addClass("dark-mode");
        localStorage.setItem("theme", "dark-mode");
    });
});

✔️ Less flickering and faster switching using CSS classes.


✅ We implemented dynamic theme switching using jQuery.
✅ Users can switch between multiple themes with smooth transitions.
LocalStorage ensures the theme preference persists across sessions.
✅ We explored both CSS file swapping and CSS class toggling methods.

Would you like further enhancements, such as auto-detecting system themes or custom color pickers? Let me know!

Leave a Reply

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