Detecting Clicks Outside Selected Text in JavaScript

In web development, there are situations where you may want to determine if a user clicks outside a specific area, such as selected text or an element.

This can be useful for various purposes, like closing a dropdown when the user clicks outside of it.

In this article, we'll explore how to check if users click outside of selected text or an element using JavaScript.

Detecting Clicks Outside an Element

To detect clicks outside a specific element, you need to add a click event listener to the document or a container element that surrounds the target area.

When a click occurs, you can then check if the target of the click event is the element you want to exclude or not.

Here's a step-by-step guide:

1. HTML Structure

First, create your HTML structure. You might have a container element with text or any other content you want to consider as "selected text."

<div id="container">
    <p>This is some selected text.</p>

2. JavaScript Logic

Now, let's add the JavaScript logic to check for clicks outside the selected text area.

We'll listen for click events on the document and verify if the target of the click is not within the container.

const container = document.getElementById('container');

// Add a click event listener to the document
document.addEventListener('click', function (event) {
    const isClickInsideContainer = container.contains(;

    // If the click is outside the container, take action
    if (!isClickInsideContainer) {
        // Perform your desired action here, e.g., close a dropdown
        console.log('Click is outside the container.');

In this code:

3. Customization

You can customize the logic to perform various actions when a click occurs outside the container.

Common use cases include closing a dropdown, hiding a modal, or resetting a selection. The possibilities are endless.

Browser Compatibility

This method is widely supported in modern web browsers. However, it's always a good practice to test your code across different browsers to ensure it works as expected, especially if you're developing for older or less common browsers.


Detecting clicks outside a specific area or element in JavaScript is a valuable technique for creating user-friendly web interfaces.

By following the steps and code provided in this article, you can easily implement this behavior in your web applications and enhance the user experience by responding to user interactions effectively.