Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

303
Views
My JS for detecting light/dark mode doesn't work right

This code is meant to detect if a user has a previously chosen color theme, and if not it should check whether they have dark mode enabled and set that corresponding theme, otherwise just set the theme to light mode. However, when I load up the page in incognito mode (so there's no localStorage data), no color theme loads. And when I go to a page with different code (code with the localStorage part but no matchMedia), choose a color theme, and go back to this page, that color theme doesn't show up either. I think there might be a simple syntax error because the code looks fine but it doesn't work for some reason.

function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
}

(function() {
    if (localStorage.getItem('theme')) {
        setTheme(localStorage.getItem('theme'))
    } else {
        window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
            if (event.matches) {
                setTheme('theme-simple-dark')
            } else {
                setTheme('theme-simple-light')
            }
        })
    }
}());
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In line with my comments, here's the reworked code. I also did a bit of DRYing up. Again, I have not tested it, may contain errors. setTheme is unchanged from yours.

function setThemeBool(dark) {
    if (dark) {
        setTheme('theme-simple-dark');
    } else {
        setTheme('theme-simple-light');
    }
}

(function() {
    const storedTheme = localStorage.getItem('theme');
    const themeQuery = window.matchMedia('(prefers-color-scheme: dark)');
    // is anything stored from before?
    if (storedTheme) {
        // yes, use that
        setTheme(storedTheme);
    } else {
        // no, ask the browser
        setThemeBool(themeQuery.matches);
    }
    // regardless, from now on, if the theme changes, switch accordingly
    themeQuery.addEventListener('change', event => {
        setThemeBool(event.matches);
    });
}());
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!