Are there easy methods than this js code for activating dark mode?

I have written some code to switch between Dark and Light modes in a website. But I had to write very big css file for that. I’ve used Java script for my switcher.

I’ve written tis code

function darkMode() 
{
var element = document.body;
var content = document.getElementById("DarkModetext");
element.className = "dark-mode";
content.innerText = "Dark Mode is ON";
}
function lightMode() 
{
var element = document.body;
var content = document.getElementById("DarkModetext");
element.className = "light-mode";
content.innerText = "Dark Mode is OFF";
}

Help me plese with another method for switching modes.

And the css file is too large for here.

CSS

:root {
  --background-color: #fff;
  --text-color: #000;
  --link-color: #007bff;
  /* Add more variables as needed */
}

.dark-mode {
  --background-color: #121212;
  --text-color: #fff;
  --link-color: #6699ff;
  /* Add more variables as needed */
}

body {
  background-color: var(--background-color);
  color: var(--text-color);
}

a {
  color: var(--link-color);
}

/* Other elements that need to change color */

JavaScript:

JavaScript

function toggleDarkMode() {
  const body = document.body;
  body.classList.toggle('dark-mode');

  const content = document.getElementById("DarkModetext");
  content.textContent = body.classList.contains('dark-mode') ? 'Dark Mode is ON' : 'Dark Mode is OFF';
}

HTML

<button onclick="toggleDarkMode()">Toggle Dark Mode</button>
<p id="DarkModetext">Dark Mode is OFF</p>

Explanation:

  1. CSS Variables: Define CSS variables in the :root selector to store color values and other properties.
  2. Dark Mode Class: Create a .dark-mode class that overrides the default CSS variables with values appropriate for dark mode.
  3. JavaScript Function: The toggleDarkMode() function toggles the .dark-mode class on the body element. This effectively switches between the default and dark mode styles.
  4. Content Update: The function also updates the text content of the DarkModetext element to indicate the current mode.

Advantages of this approach:

  • Reduced CSS: By using CSS variables, you can centralize style definitions and avoid repeating the same properties for both light and dark modes.
  • Flexibility: You can easily add or modify CSS variables to customize the appearance of your website without needing to rewrite entire stylesheets.
  • Maintainability: The code becomes more organized and easier to understand.
  • Efficiency: The JavaScript code is concise and efficient, focusing on toggling the class and updating the text content.

This approach provides a more efficient and maintainable way to implement dark mode switching in your website.