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

196
Views
Light and Dark mode based on system setting and button click in html

I have the following code on my website where I am trying to set light or dark mode based on the settings of the users system/browser as well as the ability to change the setting based on a button press.

What I want to happen is:

  1. It is daytime orthe users browser is set to light. The website loads the light.css and the button shows the moon icon to switch to the light theme.
  2. It is night time or the user has their theme set to dark mode. The website loads the dark.css theme and the icon in the button switches to the sun.

Perhaps I am missing something here to get it all functioning correctly? Mainly the buttons do not switch.

function lightDark() {
  var el = document.querySelectorAll(".light, .dark")
  if (el.href.match("light.css")) {
    el.href = "dark.css";
  } else {
    el.href = "light.css";
  }
}

<
script type = "text/javascript" >
  $('#lightDarkToggle').click(function() {
      if (window.matchMedia('prefers-color-scheme: dark').matches) {
        $(this).find('i').toggleClass('fa-sun'),
          el.href = "dark.css";

      } else {
        $(this).find('i').toggleClass('fa-moon'),
          el.href = "light.css";
      }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link class="light" rel="stylesheet" href="light.css" media="(prefers-color-scheme: no-preference), (prefers-color-scheme: light)" />
<link class="dark" rel="stylesheet" href="dark.css" media="(prefers-color-scheme: dark)" />

<button id="lightDarkToggle" onclick="lightDark()"><i class="fas fa-moon"></i></button>

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

I think this line var el = document.querySelectorAll("#light, #dark") should be var el = document.querySelectorAll(".light, .dark"), because your link tags have a class, not an id.

Another thing, in your second script tag, you try to update el.href, but in this function, el is never defined. It has been defined in another function (lightDark()), so it is not accessible anymore at the end of it.

about 4 years ago · Santiago Trujillo 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!