Table of Contents
JavaScript makes it easy to control the user experience of the user.
One of the most useful things to do is being able to toggle classes on elements. This is useful for things like showing and hiding elements, or changing the appearance of an element.
In this post, we will look at how to toggle CSS classes using JavaScript.
How to toggle CSS classes
Let's say we have a button that we want to toggle the class of when it is clicked.
HTML<body>
<div class="enabled">Hello World</div>
<button class="toggle">Toggle</button>
</body>
The expectation is that when you click the button, the class of the div will be toggled from enabled to disabled and back again.
We can make use of the built-in classList property of the element and use the toggle method to toggle the class.
The classList property is a read-only property that returns a live DOMTokenList collection of the class attributes of the element. This collection contains the list of classes of the element. You can then use the toggle method to toggle a class value; i.e., if the class exists, it is removed and if it doesn't, it is added.
JAVASCRIPTconst toggle = document.querySelector(".toggle");
const div = document.querySelector("div");
toggle.addEventListener("click", () => {
div.classList.toggle("enabled");
div.classList.toggle("disabled");
});
We can put this inside of a click listener on the button. When the button is clicked, we can run the code to toggle the class.
Then you can style each class however it makes sense:
CSS.enabled {
background-color: green;
}
.disabled {
background-color: red;
}
Keep in mind that you don't need to toggle between two different classes, you can also just toggle a single class:
JAVASCRIPTdiv.classList.toggle("enabled");
This will toggle the class of the div between enabled and nothing.
Conclusion
In this post, we learned how to toggle CSS classes using JavaScript.
Simply use the classList property of the element and use the toggle method to toggle the class.
Thanks for reading!
Managing PHP Dependencies with Composer
Create an RSS Reader in Node
Getting Started with Electron
Git Tutorial: Learn how to use Version Control
Best Visual Studio Code Extensions for 2022
Learn how to use v-model with a custom Vue component
How to Scrape the Web using Node.js and Puppeteer
Build a Real-Time Chat App with Node, Express, and Socket.io
Getting User Location using JavaScript's Geolocation API
Building a Real-Time Note-Taking App with Vue and Firebase
Using Axios to Pull Data from a REST API
How To Create a Modal Popup Box with CSS and JavaScript
