← Back toHTML DOM

Check if users click outside of selected text

Written byPhuoc Nguyen
Category
Level 1 — Basic
Created
02 Sep, 2023
If you need to know when a user clicks outside of a specific element or text selection on a web page, you can use JavaScript and the Document Object Model (DOM) to get the job done.
First, add an event listener to the `document` object to detect clicks anywhere on the page. This way, you can capture clicks that happen outside of the selected text.
document.addEventListener('click', (e) => {
// Code to execute when the user clicks outside of the selected text
// ...
});
Next, to figure out if the click happened inside or outside of the selected text, you'll need to retrieve the current selection. This can be done easily with the `getSelection()` method.
const selection = window.getSelection();
You can use the `containsNode()` method to check if a click occurred outside of the selected text. This method requires two arguments: the node to check and a `boolean` value that indicates whether the node should be checked for partial inclusion in the selection.
const clickedElement = e.target;
if (!selection.containsNode(clickedElement, true)) {
// ...
}
Here's the complete JavaScript DOM code to check if users click outside of selected text.
document.addEventListener('click', (e) => {
const selection = window.getSelection();
const clickedElement = e.target;
if (!selection.containsNode(clickedElement, true)) {
// Code to execute when the user clicks outside of the selected text
// ...
}
});
With this code, you can detect when a user clicks outside of a selected text on your web page. This allows you to execute the appropriate code to handle this event and take necessary actions.

See also

Questions? 🙋

Do you have any questions? Not just about this specific post, but about any topic in front-end development that you'd like to learn more about? If so, feel free to send me a message on Twitter or send me an email. You can find them at the bottom of this page.
I have a long list of upcoming posts, but your questions or ideas for the next one will be my top priority. Let's learn together! Sharing knowledge is the best way to grow 🥷.

Recent posts ⚡

Newsletter 🔔

If you're into front-end technologies and you want to see more of the content I'm creating, then you might want to consider subscribing to my newsletter.
By subscribing, you'll be the first to know about new articles, products, and exclusive promotions.
Don't worry, I won't spam you. And if you ever change your mind, you can unsubscribe at any time.
Phước Nguyễn