Best Light/dark Mode Theme Toggle in Javascript

Best Light/dark Mode Theme Toggle in Javascript

To create a light/dark mode theme toggle in JavaScript, you can use the following code. This implementation uses the HTML data-* attribute to store the user's preference for the theme (light or dark) and the localStorage API to persist the theme choice across page reloads.

Here's the HTML structure:

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Light/Dark Mode Toggle</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="theme-toggle" data-theme="light">Toggle Theme</div>
    <script src="script.js"></script>
</body>
</html>

The styles.css file should contain the styling for both the light and dark themes.

Next, in the script.js file, you can use JavaScript to implement the theme toggle functionality:

javascriptCopy codedocument.addEventListener('DOMContentLoaded', function () {
  const themeToggle = document.querySelector('.theme-toggle');
  const body = document.body;

  // Check if the user has a preference stored in localStorage
  const storedTheme = localStorage.getItem('theme');
  if (storedTheme) {
    body.setAttribute('data-theme', storedTheme);
  }

  // Function to toggle the theme
  function toggleTheme() {
    const currentTheme = body.getAttribute('data-theme');
    const newTheme = currentTheme === 'light' ? 'dark' : 'light';

    // Update the data-theme attribute and save the preference in localStorage
    body.setAttribute('data-theme', newTheme);
    localStorage.setItem('theme', newTheme);
  }

  // Event listener for the theme toggle button
  themeToggle.addEventListener('click', toggleTheme);
});

In this implementation, the toggleTheme function will switch the theme between light and dark by toggling the data-theme attribute on the body element. The user's preference is saved in the localStorage and retrieved on page load to set the initial theme.

By following this approach, users can have a seamless light/dark mode experience, and their preference will persist across visits to the website.

GET REMOTE DEVELOPER JOBS: SOURCEBAE.COM