Home > Net >  Cycle through 2 classes on `html` after clicking a link/toggle
Cycle through 2 classes on `html` after clicking a link/toggle

Time:09-17

I currently have a toggle that when clicked adds/removes a class to the html tag.

I'd like to update this so if you click after the original class is added the class is changed to .new-mode rather than removing the current class and the html tag being class-less. If the link is clicked again, it will then return to the default state.

So in essence it's got 3 states:

  1. No class (default / on load)
  2. Class One added (on 1st click)
  3. Class One removed, Class Two added (on 2nd click)

Then on the next click it would return to the default state without a class. So essentially just cycling through 2 classes on click. You can see I have the 1st toggle working in my example - but I'm unsure how to target the next click(s) and I'd really appreciate some help.

const html = document.querySelector('html');
const button = document.querySelector('.contrast__link');
button.addEventListener('click', e => {
  e.preventDefault();
  html.classList.toggle('dark-mode');
});
html { background: white; color: black; }
.dark-mode { background: black; color: white;}
.new-mode { background: blue; color: white;}
<p >Click here</p>

CodePudding user response:

Check what the current state is and handle the transition to the next state. Since you have a reference to the html element, you can use its classList property to see which classes are currently applied to it.

The return value is not an array, it's a DOMTokenList, so be sure to use DOMTokenList.contains() instead of Array#includes. The collection also supports adding, removing, and toggling one or more classes.

The simplest way to check and change the state is an if-else chain:

const html = document.querySelector('html');
const button = document.querySelector('.contrast__link');
button.addEventListener('click', e => {
  e.preventDefault();
  if (html.classList.contains('dark-mode')) {
    html.classList.remove('dark-mode');
    html.classList.add('new-mode');
  }
  else if (html.classList.contains('new-mode')) {
    html.classList.remove('new-mode');
  }
  else {
    html.classList.add('dark-mode');
  }
});
html { background: white; color: black; }
.dark-mode { background: black; color: white;}
.new-mode { background: blue; color: white;}
<p >Click here</p>

  • Related