Detect click outside of element with JavaScript

When building a web application, you may need to detect when a user clicks outside of a specific HTML element. This is often useful for closing (custom) dropdown menus, modals, or other UI components when the user interacts with the rest of the page. In this guide, I will show you how to implement this functionality using plain JavaScript.

Basic approach

We implement a click event listener on the document (or a specific HTML element). Inside the event handler, we check if the clicked element is inside the target element using the contains method. If the clicked element is outside the target element, we can execute the desired logic (e.g., close a dropdown menu).

Implementation

For the example we use a custom dropdown component, but the same logic can be applied to other UI components as well.

<div id="dropdown">
    <div class="dropdown-head">
        <span>Selected option</span>
    </div>
    <div class="dropdown-options">
        <ul>
            <li>Option 1</li>
            <li>Option 2</li>
            <li>Option 3</li>
        </ul>
    </div>
</div>

With JavaScript, an event listener is added to the document. Inside the event handler we check if the clicked element is inside the dropdown element. If the click is outside the dropdown element, we can hide the dropdown options.

document.addEventListener('click', (event) => {
    const dropdownElement = document.getElementById('dropdown');
    const clickedElement = event.target;

    // Is the clicked element inside the dropdown element?
    if (dropdownElement.contains(clickedElement)) {
        // Yes, the click is inside the dropdown element.
    } else {
        // No, the click is outside the dropdown element.
        // Hide the dropdown options and/or perform other actions here.
    }
});