LetterThirteen
LetterThirteen

Reputation: 320

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>

Upvotes: 0

Views: 2120

Answers (1)

Dylan El Bar
Dylan El Bar

Reputation: 933

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.

Upvotes: 1

Related Questions