How to Add Transition While Switching from Light Mode to Dark Mode in JavaScript

Abstract: Resolve jarring instant color changes when toggling dark mode by applying CSS transitions to the body element and managing state via class toggling.

Created: 2026-10-12 by
To add a smooth transition when switching from light mode to dark mode in JavaScript, you must apply CSS transitions to the relevant properties and toggle a class on the <body> element rather than changing inline styles directly. This approach ensures that browsers can animate the color changes over time instead of snapping instantly. The following guide explains how to implement this using standard HTML, CSS, and vanilla JavaScript without relying on external libraries or complex frameworks.

Understanding the Transition Mechanism

The core issue with implementing dark mode is that most developers attempt to change colors via JavaScript by modifying inline styles or individual CSS variables dynamically. While this works for immediate application, it bypasses the browser's rendering pipeline for animations. To achieve a smooth fade effect, you need to leverage CSS transitions. CSS transitions allow you to specify which properties should be animated and how long the animation should take. When you toggle a class on the root element (usually <body> or <html>), the browser compares the computed styles before and after the class change. If there are differences in properties like background-color or color, and those properties have a transition defined, the browser interpolates between the two states. This method is superior because it keeps your styling logic in CSS where it belongs, while JavaScript handles only the state management. It also prevents the "flash of unstyled content" or jarring jumps that occur when scripts execute asynchronously. By separating concerns, you ensure that the visual experience remains consistent across different devices and browsers.

Setting Up the CSS Styles

First, define your base styles for the light mode. Then, create a separate set of styles for the dark mode using a specific class, such as .dark-mode. The key is to apply the transition property to all elements that will change color. Start by targeting the body element. You want every text color and background color within the document to transition smoothly. However, applying transitions to every single element individually can be performance-intensive. A more efficient approach is to use the universal selector or target common containers.
/* Base Light Mode Styles */
body {
  background-color: #ffffff;
  color: #000000;
  transition: background-color 0.3s ease, color 0.3s ease;
}

/* Dark Mode Styles */
body.dark-mode {
  background-color: #121212;
  color: #ffffff;
}
In this example, the transition property specifies that both background-color and color should change over 0.3 seconds using an ease timing function. The ease function provides a natural deceleration effect, making the change feel less robotic. You can adjust the duration and timing function to suit your design preferences. For instance, a faster transition might be better for mobile users who prefer quick interactions. If you have other elements like cards, headers, or buttons, they may need their own transition rules if they do not inherit from the body. Ensure that any custom components also include the transition property to maintain consistency throughout the interface. This step is crucial because inherited properties do not always trigger transitions automatically if the parent element does not explicitly define them.

Implementing the JavaScript Toggle Logic

With the CSS prepared, the next step is to write the JavaScript code that toggles the .dark-mode class. This script should listen for a user action, such as clicking a button or a toggle switch. It is important to check the current state of the class before adding or removing it. Use the classList.toggle() method for simplicity. This method adds the class if it is not present and removes it if it is already present. This reduces the amount of conditional logic required in your code. Additionally, you should persist the user's preference using localStorage so that the theme remains consistent across page reloads.
const toggleBtn = document.getElementById('theme-toggle');
const body = document.body;

// Check for saved user preference
const currentTheme = localStorage.getItem('theme');
if (currentTheme === 'dark') {
  body.classList.add('dark-mode');
}

toggleBtn.addEventListener('click', () => {
  body.classList.toggle('dark-mode');
  
  // Save preference to local storage
  if (body.classList.contains('dark-mode')) {
    localStorage.setItem('theme', 'dark');
  } else {
    localStorage.setItem('theme', 'light');
  }
});
This script first checks if the user has previously selected a dark theme. If so, it applies the class immediately upon loading. When the button is clicked, it toggles the class and updates the local storage. This ensures that the transition happens seamlessly whether the user is visiting the site for the first time or returning after some time. It is also advisable to handle system-level preferences. Many operating systems allow users to set a global dark mode preference. You can detect this using the prefers-color-scheme media query in CSS or via JavaScript matchMedia API. If no local storage preference exists, you can default to the system setting. This enhances accessibility and aligns with user expectations. For more advanced implementations, consider integrating with component libraries or preprocessor files. If you are using SCSS for your project, you might find it useful to manage these variables centrally. See importing scss variables into another file for tips on organizing your style assets efficiently.

Handling Edge Cases and Performance

While the basic implementation covers most use cases, there are several edge cases to consider. One common issue is the flash of incorrect theme on initial load. To prevent this, place your JavaScript in the <head> section or use a small inline script that runs before the DOM content loads. This ensures the correct class is applied before the browser paints the initial frame. Another consideration is performance. Animating too many properties simultaneously can cause layout thrashing or high CPU usage, especially on lower-end devices. Limit the number of transitioning properties to only those that are visually necessary. Avoid animating properties that trigger layout recalculations, such as width or height, unless absolutely needed. You can also improve the user experience by providing visual feedback on the toggle button itself. For example, an icon that rotates or changes shape when the theme switches helps reinforce the action. Ensure that these icons also respect the transition timings to maintain a cohesive feel. For sites that rely heavily on dynamic content loading, such as infinite scroll tables, ensure that new elements inherit the correct styles immediately. See table loading data with each scroll for strategies on managing dynamic content injection without breaking theme consistency.

Frequently Asked Questions

Why does my dark mode flicker on page load?

This usually happens because the JavaScript runs after the initial paint. To fix it, move your theme-checking script into the head tag or use a tiny inline script that sets the class before the body renders. This prevents the browser from displaying the light theme briefly.

Can I use CSS variables for dark mode transitions?

Yes, CSS variables are ideal for this. Define your colors as variables on the :root selector and update their values when the .dark-mode class is added. Transitions work on variables just as well as direct properties, offering greater flexibility for complex themes.

How do I detect the user's system dark mode preference?

You can use the window.matchMedia() API with the '(prefers-color-scheme: dark)' query. This allows your JavaScript to automatically apply the dark theme if the user's operating system is set to dark mode, provided no local storage override exists.

Is it better to use JavaScript or pure CSS for toggling?

Pure CSS cannot toggle classes based on clicks without hidden checkboxes or radio buttons, which limits interactivity. JavaScript is necessary for handling events, saving preferences, and responding to dynamic conditions like system settings, making it the standard choice for robust implementations.

What causes laggy transitions on mobile devices?

Laggy transitions are often caused by animating properties that trigger layout or paint recalculations, such as box-shadow or large gradients. Stick to animating simple properties like opacity, transform, and color. Also, ensure your CSS is minified and served efficiently to reduce parsing time.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More