最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - onClick() function and darkmode toggle function - Stack Overflow

programmeradmin3浏览0评论

So, I have a dark mode button that works fine when light mode is enabled but if I use the auto detect css media query and page starts in darkmode the button will not do anything because it's already in dark mode. My question is how can I make the same darkmode button work and switch page to light mode instead of adding a sperate button for light mode?

HTML

<button onclick="dark_mode()"> dark mode </button>

CSS

.dark-mode {
  css code for dark mode here
}

JS

 function dark_mode() {
    var element = document.body;
    element.classList.toggle("dark-mode");
 }

So, I have a dark mode button that works fine when light mode is enabled but if I use the auto detect css media query and page starts in darkmode the button will not do anything because it's already in dark mode. My question is how can I make the same darkmode button work and switch page to light mode instead of adding a sperate button for light mode?

HTML

<button onclick="dark_mode()"> dark mode </button>

CSS

.dark-mode {
  css code for dark mode here
}

JS

 function dark_mode() {
    var element = document.body;
    element.classList.toggle("dark-mode");
 }
Share Improve this question asked Feb 14 at 20:13 user29519291user29519291 12 bronze badges 3
  • I don't see the problem with the current code. Why does it already start in dark mode? What do you mean by auto detect css media query? – Barmar Commented Feb 14 at 20:54
  • 2 Please post a minimal reproducible example. – Barmar Commented Feb 14 at 20:55
  • I don't understand your question. dark-mode is detected in CSS by @media (prefers-color-scheme: dark) it has nothing to do with a CSS class, even if you name it dark-mode – Mister Jojo Commented Feb 14 at 22:04
Add a comment  | 

1 Answer 1

Reset to default 1

Lets start with finding out what mode the user prefers:

let isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

A better name for this function could be toggleColorScheme

<button onclick="toggleColorScheme()"> Toggle color scheme </button>

Lets define the function. Make sure it can access isDarkMode.

const toggleColorScheme = () => {
  isDarkMode ^= 1 // Toggle `isDarkMode` between 0 and 1

  if (isDarkMode) document.body.classList.add('dark-mode');
  else document.body.classList.remove('dark-mode');
}

I disrecommend using classList.toggle() as you don't have 100% certainty over when the .dark-mode class is present or not.

发布评论

评论列表(0)

  1. 暂无评论