DEV Community

Yiğit Kaan Korkmaz
Yiğit Kaan Korkmaz

Posted on

The CSS classList.toggle Method (And a surprise feature of it)

Hello everyone! Today i want to talk to you about the CSS classList.toggle method and an interesting feature of it that i've found.

So, let's begin by learning what the method itself does:

<p>Lorem ipsum</p>
Enter fullscreen mode Exit fullscreen mode
.blue {
  color: blue;
}
Enter fullscreen mode Exit fullscreen mode
const p = document.querySelector("p");

p.classList.toggle("blue");

setTimeout(() => {
  p.classList.toggle("blue");
}, 5000)
Enter fullscreen mode Exit fullscreen mode

So, above is a snippet of an HTML page with the p tag with the text "Lorem ipsum", and what we just did in the js part is, we selected the tag first, and then "toggled" the "blue" class of it.

And 5 seconds later, we just "toggled" the "blue" class again.

What that means is JS basically checks if the "blue" class exists in the element, it removes it, if it does not, it simply adds the element.

This can be used in a lot of ways! To make more reactive content and to just simply hide things in a dynamic manner, the "classList.toggle" method is great!

But what about the special part i just talked to you about?

Take the program below as an example:

<p>Lorem ipsum</p>

<button>Increment</button>
Enter fullscreen mode Exit fullscreen mode
.blue {
  color: blue;
}

.red {
  color: red;
}
Enter fullscreen mode Exit fullscreen mode
const p = document.querySelector("p");
const incrementBtn = document.querySelector("button");
let i = 0;

p.classList.toggle("blue");

incrementBtn.addEventListener("click", (_) => {
  i++;
  if (p) {
    p.classList.toggle("red", i > 3);
    p.classList.toggle("blue", i <= 3);
  }
});
Enter fullscreen mode Exit fullscreen mode

But Kaan, what is the second boolean property you just gave to it? I hear you asking, well that my friend, is the "force" property of the toggle method. Basically, if that method is true, the class is immediately added to the element, and if not, it is immediately removed.

So i used it to make a counter, that when it gets above 3, the text turns red, and if not, the text is blue!

Using this property you can add or remove things based on a conditional, which is amazing and very useful!

I hope today's article has been any use to you, if so, i'd appreciate your like!

And if you found any problems in the code or in any information i've given, please feel free to leave a comment and tell me about it, i'd love to hear your opinion on things!

Until then, see you in the next article!

Top comments (1)

Collapse
 
kaankorkmaz profile image
Yiğit Kaan Korkmaz

That's a nice way you used the property there! I agree with it, cheers!