Toggle class in vanilla JavaScript Vanilla JS
Toggling a class on an HTML element with JavaScript is the process of adding or removing a class depending on whether the element already has the class or not. It can be useful to toggle (add or remove) a class on an HTML element when something is clicked like a menu icon for example. Toggling a class with JavaScript allows you to do things like apply certain CSS styles only when a specific class is present. This is how to toggle (add or remove) a class in vanilla JavaScript.
element.classList.toggle('class-name');
element.classList.toggle('class-name');
detects if the class "class-name" is already added to the element or not and if it's there, it will remove the class but if it's not there it will add the class.
Here is a full example with a selected element and event listener:
<a href="#" id="toggle">Menu</a>
//JavaScript
let toggle = document.querySelector('#toggle');
toggle.addEventListener('click', function(e) {
e.preventDefault();
toggle.classList.toggle('x');
});
This selects the element with the id of 'toggle' and stores it in a variable, adds a click event listener, prevents the user from being taken to the href URL of the anchor and adds or removes the class 'x' each time it is clicked.
You can use something like this for making an animated hamburger menu icon which turns into an x icon when clicked and the menu is showing.
When using an <a>
(anchor) element for purposes like a toggle or tab instead of standard links, you can leave the href
value as '#'. The e.preventDefault()
stops an anchor from sending the user to its href URL when it is clicked.
For more control, you can manually add and remove the class like this:
toggle.addEventListener('click', function(e) {
e.preventDefault();
if (toggle.classList.contains('x')) {
toggle.classList.remove('x');
} else {
toggle.classList.add('x');
}
});
In this case, we are using a conditional statement to check if
the element already has the class using element.classList.contains("class-name")
. If the element already has the class, this evaluates to true and the code in the if
code block runs which removes the class, and if it doesn't already have the class, the code in the else
code block runs which adds the class.
When toggling a class manually with a conditional statement like this, you could also write more code inside each code block to perform other things at the same time depending on if the element already had the class or not.
Thanks for reading.
Ryan
Published on 22 Mar 2019 (on a previous domain)
Last modified on 14 Aug 2022