Toggle class by adding the class name when element is clicked and remove when clicked outside
In this article, the task is to toggle a CSS class when clicked on that element and remove that particular class when clicked outside that element, that is, anywhere else in the HTML document.
- We will first select the element on which the class has to be toggled and the entire HTML document using the querySelector() method.
- Next, we need to add the ‘click’ event listeners to both of the selected elements.
- In the event listener of the element to be clicked, we will add the required CSS class using the classList.add() method.
- In the event listener of the HTML document, we will first check if the clicked target is the above required element and then remove the class using the classList.remove() method, thereby toggling the class when clicked outside the above element.
Example: In this example, a button is defined in the HTML document on which the ‘active’ CSS class would be added once it is clicked. This ‘active’ class will also be removed from the button once we click anywhere else in the HTML document.