I am trying to implement a light mode/dark mode toggle on a website. The toggle itself is working as expected, but I can't figure out how to also make it switch between style sheets. I am new to JS so the CSS/HTML is there, but I can't get the script right.
So this is what I have so far that works on its own before trying to switch style sheets...
CSS:
<head>
<link rel="stylesheet" type="text/css" href="light-styles.css" id="theme-link">
</head>
<style>
/* Light Mode / Dark Mode Switch */
#switchposition {
position: relative;
display: flex;
flex-direction:
column-reverse;
justify-content: start;
align-items: start;
}
#modelabel {
position: relative;
font-size: 14px;
color: #dc92b9;
transition: .4s;
margin-bottom: 0;
padding-bottom: 0;
}
.switch {
position: relative;
width: 50px;
height: 25px;
}
.switch input {
opacity: 0;
height: 0;
width: 0;
}
.slider {
top: 0;
bottom: 0;
left: 0;
right: 0;
transition: 0.4s;
background-color: #dc92b9;
border-radius: 34px;
position: absolute;
cursor: pointer;
}
.slider::before {
content: '';
position: absolute;
background-color: #f8e8ef;
width: 15px;
height: 15px;
border-radius: 50%;
left: 5px;
bottom: 5px;
transition: 0.4s;
}
.switch input:checked + .slider::before {
transform: translateX(25px);
background-color: #6d5f94;
}
.switch input:checked + .slider {
background-color: #101010;
}
</style>
HTML:
<div id="switchposition">
<p id="modelabel">Light Mode</p>
<label class="switch">
<input onclick="toggle()" type="checkbox" id="checkBox">
<span class=" slider"></span>
</label>
</div>
JS:
function toggle(){
var input = document.getElementById("checkBox");
if(input.checked == true){
modelabel.style.color ="#6d5f94";
} else{
modelabel.style.color ="#dc92b9";
}
var x = document.getElementById("modelabel");
if (x.innerHTML === "Light Mode") {
x.innerHTML = "Dark Mode";
} else {
x.innerHTML = "Light Mode";
}
}
This is what I tried to put into the code to also make it switch between css sheets. When I add this in nothing breaks, but it does not work either.
function toggle(){
var input = document.getElementById("checkBox");
if(input.checked == true){
modelabel.style.color ="#6d5f94";
} else{
modelabel.style.color ="#dc92b9";
}
var input = document.getElementById("theme-link")
if (input.checked == true) {
theme.setAttribute('href', 'dark-styles.css');
} else {
theme.setAttribute('href', 'light-styles.css');
}
var x = document.getElementById("modelabel");
if (x.innerHTML === "Light Mode") {
x.innerHTML = "Dark Mode";
} else {
x.innerHTML = "Light Mode";
}
}