How to Make Light and Dark Mode Toggles Using HTML and JavaScript

Photo by Josh Boot on Unsplash

How to Make Light and Dark Mode Toggles Using HTML and JavaScript

This is a continuation of the article How to Implement Auto Light and Dark Mode Using Only HTML

Auto light and dark mode is indeed easy, but it would be better if users were given the option to change the mode within the web page. This can be implemented using a JavaScript button.

HTML

First, make sure you have applied the theme mode in the meta section, and then add a button to change the mode.

<head>
  <meta name="color-scheme" content="dark light">
</head>

<body>
  <h1>Hello world!</h1>
  <button id="theme-toggle">change theme</button>
</body>

JavaScript

Change the meta attribute using metaTag.setAttribute()

const metaTag = document.querySelector('meta[name="color-scheme"]');

document.getElementById('theme-toggle').addEventListener('click', () => {
  const currentTheme = metaTag.content === 'dark light' ? 'light' : 'dark light';
  metaTag.setAttribute('content', currentTheme);
});

And it's done!

CodePen

Here is the result of its implementation