Sling Academy
Home/JavaScript/JavaScript: Detect a click outside an HTML element

JavaScript: Detect a click outside an HTML element

Last updated: February 19, 2023

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!');
       }
}

Below is the complete example with Javascript as well as HTML and CSS.

Example preview

We have a simple webpage that displays a red box. When you click inside the box, the console will print “You clicked inside the box!”. Otherwise, it will show “You clicked outside the box!”.

The code:

<!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>

If you have any questions about this the code snippet above, please leave a comment. We’re more than happy to help.

Next Article: JavaScript: 4 Ways to Get the Width & Height of an Element

Previous Article: The Modern JavaScript DOM Cheat Sheet

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Can JavaScript programmatically bookmark a page? (If not, what are alternatives)
  • Dynamic Import in JavaScript: Tutorial & Examples (ES2020+)
  • JavaScript: How to implement auto-save form
  • JavaScript: Disable a Button After a Click for N Seconds
  • JavaScript: Detect when a Div goes into viewport
  • JavaScript Promise.any() method (basic and advanced examples)
  • Using logical nullish assignment in JavaScript (with examples)
  • Understanding WeakRef in JavaScript (with examples)
  • JavaScript Numeric Separators: Basic and Advanced Examples
  • JavaScript: How to Identify Mode(s) of an Array (3 Approaches)
  • JavaScript: Using AggregateError to Handle Exceptions
  • JavaScript FinalizationRegistry: Explained with Examples
  • JavaScript String replaceAll() method (with examples)
  • Nullish Coalescing in JavaScript: A Developer’s Guide
  • JavaScript Promise.allSettled() method (with examples)
  • JavaScript: Checking if the current window is a popup
  • JavaScript: Checking if the current window is fullscreen
  • JavaScript: Checking if a Div element is visible
  • JavaScript: How to programmatically reload/close the current page