I'm trying to make a switch change the background color of a div using classList.toggle, but it isn't working and I don't know why, even though it's probably very simple. Can someone clarify this to me, please?
var toggle = document.getElementById('switch')
toggle.onclick = function() {
document.getElementById('testDiv').classList.toggle('test')
}
#testDiv {
width: 250px;
margin: auto;
margin-top: 16px;
background-color: white;
}
.test {
background-color: black !important;
}
<label class="switch" id="switch" onclick="myFunction()">
<input type="checkbox">
<span class="slider round"></span>
</label>
<div id="testDiv">
<p>
plain text
</p>
</div>
You can call the myFunction when the user clicks the checkbox. Fixed the CSS file to place !important in proper position.
function myFunction(){
document.getElementById('testDiv').classList.toggle('test');
}
#testDiv {
width: 250px;
margin: auto;
margin-top: 16px;
background-color: white;
}
.test {
background-color: black !important;
color: white;
}
<label class="switch" id="switch" for="change_bg">Change background</label>
<input type="checkbox" id="change_bg" onclick="myFunction()">
<div id="testDiv">
<p>
plain text
</p>
</div>