I got this code online, I’m confused as to how I can get the background colour to change when the button is toggled. How would I get it to change colour when the html containers are .
:root {
/*========== Colors ==========*/
/*Color mode HSL(hue, saturation, lightness)*/
--line-color: hsl(234, 12%, 35%);
--active-color: hsl(234, 100%, 98%);
--inactive-color: hsl(234, 20%, 68%);
--body-color: hsl(189, 49%, 87%);
--background-colour: hsl(189, 84%, 14%);
}
* {
box-sizing: border-box;
}
body {
height: 100vh;
margin: 0;
display: grid;
place-items: center;
background-color: var(--body-color);
}
.toggle__content {
display: grid;
row-gap: 1.5rem;
}
.toggle__label {
cursor: pointer;
padding-block: .5rem;
}
.toggle__check {
display: none;
}
.toggle__rail {
position: relative;
width: 52px;
height: 4px;
background-color: var(--line-color);
border-radius: 2rem;
}
.toggle__circle {
display: block;
width: 24px;
height: 24px;
background-color: var(--body-color);
box-shadow: inset 0 0 0 4px var(--inactive-color);
border-radius: 50%;
position: absolute;
left: 0;
top: 0;
bottom: 0;
margin: auto 0;
transition: transform .4s, box-shadow .4s;
z-index: 2;
}
.toggle__border {
position: absolute;
width: 32px;
height: 32px;
background-color: var(--body-color);
border-radius: 50%;
left: -4px;
top: 0;
bottom: 0;
margin: auto 0;
transition: transform .4s;
}
/* Toggle animation effects */
.toggle__check:checked~.toggle__rail .toggle__circle {
transform: translateX(28px);
box-shadow: inset 0 0 0 12px var(--active-color);
}
.toggle__check:checked~.toggle__rail .toggle__border {
transform: translateX(28px);
}
<div class="toggle__content">
<label class="toggle__label">
<input type="checkbox" class="toggle__check">
<div class="toggle__rail">
<span class="toggle__circle"></span>
<span class="toggle__border"></span>
</div>
</label>
</div>
I want to change it from –body-color: hsl(189, 84%, 14%) to –background-colour: hsl(189, 84%, 14%) when the switch is toggled
2
Answers
The best practice in this case is using the Add/Remove class with JS, the background color that will be applied is the one added by the class, due to the specificity rule on CSS.
First add this class to your CSS:
Then add this code on the script tag, it basically waits for the DOM to be loaded then add the specified class when the checkbox is checked and remove if it’s not:
If you want the opposite, just change the
.add
and.remove
positionsThe easiest change is to simply listen for the
input
(orchange
if you prefer) event, and then toggle a class on the<body>
element based on the checked/unchecked state of the<input>
as below, with explanatory comments in the code: