Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

197
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda