Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda