The functionality implemented in the resize()
function involves checking for the presence of the switch
class on the body
element. If the class is present, it is removed upon firing the resize
function; otherwise, the class is added.
However, a problem arises with the snippet below when the button is clicked – it fails to act as a toggle. Instead, it only registers one click and does not restore to its original state.
Why is this basic JavaScript code not functioning correctly, and what are some approaches to resolve this issue?
function resize() {
var body = document.querySelector( 'body' );
if( body.classList.contains( 'switch' ) ){
body.classList.remove( 'shrink' );
}
else {
body.classList.add( 'shrink' );
}
}
var switcher = document.getElementById( 'switch' );
switcher.addEventListener( 'click', resize );
p {
text-align: center;
margin-bottom: 1rem;
transition-property: color;
transition-duration: 1.5s;
}
.bar {
width: 22.5rem;
height: 10rem;
background-color: #555;
border-radius: 5rem;
position: relative;
transition-property: background-color;
transition-duration: 1.5s;
}
.knob {
width: 12rem;
height: 12rem;
background-color: #000;
border-radius: 10rem;
position: absolute;
top: 50%;
right: 0;
transform: translateY( -50% );
transition-property: right, background-color;
transition-duration: 1s, 1.5s;
}
:checked ~ label p { color: #888 }
:checked ~ label .bar { background-color: #888 }
:checked ~ label .knob {
background-color: #777;
right: 10.5rem
}
.shrink { transform: scale( 0.8 ) }
<head>
<style>
* { margin: 0 }
html { font-size: 10px }
html,
body,
main { height: 100% }
body {
transition-property: transform;
transition-duration: 1s;
}
main {
font-family: arial;
font-size: 6rem;
display: flex;
text-transform: capitalize;
}
input { display: none }
label,
p {
user-select: none;
cursor: pointer;
margin: auto;
}
</style>
</head>
<body>
<main>
<input type="checkbox" id="checkbox">
<label for="checkbox" id="switch">
<p>switch</p>
<div class="bar">
<div class="knob"></div>
</div>
</label>
</main>
</body>