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

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration