1

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>
  • 1
    A click on the label triggers a click on the input. Since you're using a delegate listener, you receive both. – connexo Jun 22 '22 at 10:38
  • What would I do to fix this error? – CodePlanB1234 Jun 22 '22 at 10:39
  • `document.body.classList.toggle('dark-mode', this.querySelector('input').checked);` as the only line of code inside your handler will get the job done. The solution is to work with `classList.toggle(className: string, force: boolean)`. – connexo Jun 22 '22 at 10:41
  • instead of adding event listener to the `button-container` give it to the `checkbox` here is the solution [SOLUTION-fiddle](https://jsfiddle.net/Hootan/jf0ko4e7/61/) – Rocky Jun 22 '22 at 10:46
  • Don't listen to `click`, listen to `change` instead, which will give you only one execution. Then use that line from my comment above. – connexo Jun 22 '22 at 10:47

0 Answers0