Open In App

Toggle class by adding the class name when element is clicked and remove when clicked outside

Last Updated : 28 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Approach: This can be easily accomplished with the help of JavaScript by following the steps below:

  • 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.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <style>
        button {
            background-color: green;
            color: white;
            padding: 10px 24px;
            font-size: 18px;
            border: none;
            font-weight: bold;
            transition: all 0.4s;
            margin: 300px;
        }
 
        .active {
            background-color: black;
        }
    </style>
</head>
 
<body>
    <button>GeeksforGeeks</button>
 
    <script>
        // Select the button on which the
        // class has to be toggled
        const btn = document.querySelector("button");
 
        // Select the entire HTML document
        const html = document.querySelector("html");
 
        // Add an event listener for
        // a click to the button
        btn.addEventListener("click", function (e) {
 
            // Add the required class
            btn.classList.add("active");
        });
 
        // Add an event listener for a
        // click to the html document
        html.addEventListener("click", function (e) {
 
            // If the element that is clicked on is
            // not the button itself, then remove
            // the class that was added earlier
            if (e.target !== btn)
                btn.classList.remove("active");
        });
    </script>
</body>
 
</html>


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads