Reputation: 320
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:
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
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