Vanilla Javascript: Detect a click outside an HTML element

Last updated on June 13, 2022 Pennywise Loading... Post a comment

With Javascript, you can easily detect if the user clicks somewhere outside a given HTML element. For example, the code snippet below shows you how to catch a click outside an element with the id of my-box:

 window.onclick = function (event) {
       var myBox = document.getElementById('my-box');

       if (event.target.contains(myBox) && event.target !== myBox) {
           console.log('You clicked outside the box!');
       } else {
           console.log('You clicked inside the box!');
       }
}

Here’s the complete example with Javascript as well as HTML and CSS:

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">

    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            padding: 40px;
            background: rgb(247, 240, 155);
        }

        #my-box {
            margin-top: 30px;
            background: rgb(206, 69, 92);
            width: 500px;
            height: 350px;
            cursor: pointer;
        }
    </style>

    <title>KindaCode.com</title>
</head>

<body>
    <h1>KindaCode.com</h1>
    <div id="my-box"></div>

    <script>
        window.onclick = function (event) {
            var myBox = document.getElementById('my-box');

            if (event.target.contains(myBox) && event.target !== myBox) {
               console.log('You clicked outside the box!');
            } else {
                console.log('You clicked inside the box!');
            }
        }
    </script>
</body>

</html>

Output:

If you want to do the same thing in React or Next.js, see this article: How to Detect a Click Outside/Inside a Component in React.

Further reading:

You can also check out our Javascript category page, TypeScript category page, Node.js category page, and React category page for the latest tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

You May Also Like