I posted a question similar to this and the solution people provided worked, but it only worked when I comment out all my other CSS code. For some reason, the CSS is interfering with the JavaScript function to work properly. I want to change the background color to black when I click the button, but I want to change it back to white when I click on it again.
<!DOCTYPE html>
<html>
<head>
<title>Light Switch</title>
<link rel="stylesheet" href="light.css" />
</head>
<body id="body">
<div id="click">
<label id="switch">
<input type="checkbox" checked>
<span class="slider"></span>
</label>
</div>
<script src="light.js"></script>
</body>
</html>
#switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
margin: 0 auto;
}
#switch input {
display: none;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: grey;
-webkit-transition: .4s;
transition: .4s;
border-radius: 34px;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
background-color: white;
bottom: 4px;
transition: .4s;
border-radius: 50%;
}
input:checked + .slider {
background-color: #1583ea;
}
input:checked + .slider:before {
transform: translateX(26px);
}
function start() {
var click = document.getElementById("switch");
click.addEventListener("click", toggle);
};
function toggle() {
var color = document.getElementById("body");
var backColor = color.style.backgroundColor;
color.style.backgroundColor = backColor === "black" ? "white" : "black";
};
start();