Hi I am trying to create a toggle function but every time I click it appears to register twice and I am guessing therefore adding and removing the class that I am wanting to toggle?
I am trying to create a simple toggle javascript function on click event but it appears to register twice in the console.
can anyone assist and let me know why this is failing and provide a code solution to the issue please.
const btnContainer = document.querySelector('.button-container');
// const bodyEl = document.body;
const bodyEl = document.body;
btnContainer.addEventListener('click', function () {
if (bodyEl.classList.contains('dark-mode')) {
bodyEl.classList.remove('dark-mode');
} else {
bodyEl.classList.add('dark-mode');
}
// bodyEl.classList.toggle('dark-mode;');
console.log('wtf');
});
.dark-mode {
background-color: red;
border: solid 20px yellow;
}
.toggle-wrapper {
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
}
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 30px;
margin-left: 1rem;
margin-right: 1rem;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: 0.4s;
transition: 0.4s;
}
.slider:before {
position: absolute;
content: '';
height: 22px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: 0.4s;
transition: 0.4s;
}
input:checked + .slider {
background-color: #2196f3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196f3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
<div class="toggle-wrapper">
<span>B&W</span>
<div class="button-container">
<label class="switch">
<input type="checkbox">
<span class="slider"></span>
</label>
</div>
<span>Color</span>
</div>