logologo
  • AI Tools

    DB Query GeneratorMock InterviewResume BuilderLearning Path GeneratorCheatsheet GeneratorAgentic Prompt GeneratorCompany ResearchCover Letter Generator
  • XpertoAI
  • AI Interviewer
  • MVP Ready
  • Resources

    CertificationsTopicsExpertsCollectionsArticlesQuestionsVideosJobs
logologo

Elevate Your Coding with our comprehensive articles and niche collections.

Useful Links

  • Contact Us
  • Privacy Policy
  • Terms & Conditions
  • Refund & Cancellation
  • About Us

Resources

  • Xperto-AI
  • Certifications
  • Python
  • GenAI
  • Machine Learning

Interviews

  • DSA
  • System Design
  • Design Patterns
  • Frontend System Design
  • ReactJS

Procodebase © 2024. All rights reserved.

Level Up Your Skills with Xperto-AI

A multi-AI agent platform that helps you level up your development skills and ace your interview preparation to secure your dream job.

Launch Xperto-AI

Implementing a Dynamic Theme Switcher (Light/Dark Mode) in Your Web Application

author
Generated by
Abhishek Goyan

14/09/2024

theme switcher

Sign in to read full article

Introduction

In today's digital landscape, the user experience is crucial, and one aspect that significantly affects this is the visual theme of your web application. With a growing awareness around eye strain and accessibility, dark mode has become increasingly popular. Implementing a dynamic theme switcher that allows your users to toggle between light and dark modes can enhance usability and give your application a modern touch.

Setting Up the Project

Before we dive into the code, let's set up a simple HTML structure for our project. We will also include some basic CSS styles to visualize the light and dark themes.

Here’s a simple HTML structure for our application:

<!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> <button id="theme-toggle">Switch to Dark Mode</button> </div> <script src="script.js"></script> </body> </html>

CSS for Themes

Next, we’ll implement the light and dark mode styles using CSS variables. This method allows us to define a set of properties that can be changed easily.

Create a styles.css file with the following content:

:root { --background-color: #ffffff; --text-color: #000000; } body { background-color: var(--background-color); color: var(--text-color); transition: background-color 0.5s ease, color 0.5s ease; } .container { text-align: center; padding: 50px; } .dark-mode { --background-color: #000000; --text-color: #ffffff; }

JavaScript for Theme Toggling

Now that we have defined our styles, we'll add functionality to switch between light and dark modes using JavaScript. We'll also implement local storage so that the user’s preference persists even after refreshing the page.

Create a script.js file and add the following code:

const toggleButton = document.getElementById('theme-toggle'); const applyTheme = (theme) => { if (theme === 'dark') { document.body.classList.add('dark-mode'); toggleButton.textContent = 'Switch to Light Mode'; } else { document.body.classList.remove('dark-mode'); toggleButton.textContent = 'Switch to Dark Mode'; } }; const toggleTheme = () => { const currentTheme = localStorage.getItem('theme') || 'light'; const newTheme = currentTheme === 'light' ? 'dark' : 'light'; localStorage.setItem('theme', newTheme); applyTheme(newTheme); }; // On initial load, check for the user's theme preference const savedTheme = localStorage.getItem('theme') || 'light'; applyTheme(savedTheme); toggleButton.addEventListener('click', toggleTheme);

How It Works

  1. CSS Variables: We defined CSS variables for background and text colors that we can switch dynamically as we toggle between themes.

  2. JavaScript Functionality:

    • We set up a button in our HTML that users will click to toggle themes.
    • The applyTheme function adds or removes the dark-mode class to the body, changing the CSS variable values based on the theme.
    • The current theme is stored in local storage, so when users return to the site, it remembers their last selection.
  3. Event Listener: We added an event listener to the button to listen for clicks and toggle the theme accordingly.

Running the Project

Make sure your HTML, CSS, and JavaScript files are connected properly and open your HTML file in a web browser. You should see a button labeled "Switch to Dark Mode." When clicked, the background color and text color will change, and the button's label will update to let users know they can switch back to light mode. Additionally, if you refresh the page, it will remember your last selection courtesy of local storage.


With the above steps, you now have a fully functional dynamic theme switcher for your web application. This small addition not only improves accessibility but also provides users with a personalized browsing experience. Let's take a moment to experiment with other design aspects or even integrate system preferences into our theme switcher!

Popular Tags

theme switcherlight modedark mode

Share now!

Like & Bookmark!

Related Collections

  • Mastering React Concepts

    24/08/2024 | ReactJS

  • React Interview Challenges: Essential Coding Problems

    14/09/2024 | ReactJS

Related Articles

  • Setting Up Your React Development Environment

    24/08/2024 | ReactJS

  • Introduction to React: Understanding the Basics

    24/08/2024 | ReactJS

  • Building a Pagination Component in React

    14/09/2024 | ReactJS

  • Build a Context-Based State Management System in React

    14/09/2024 | ReactJS

  • Building a Simple React Application: Putting It All Together

    24/08/2024 | ReactJS

  • Testing React Components with Jest and React Testing Library

    24/08/2024 | ReactJS

  • Understanding Advanced Promises in JavaScript

    20/09/2024 | ReactJS

Popular Category

  • Python
  • Generative AI
  • Machine Learning
  • ReactJS
  • System Design