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>
.blue {
color: blue;
}
const p = document.querySelector("p");
p.classList.toggle("blue");
setTimeout(() => {
p.classList.toggle("blue");
}, 5000)
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>
.blue {
color: blue;
}
.red {
color: red;
}
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);
}
});
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)
That's a nice way you used the property there! I agree with it, cheers!