Check if users click outside of selected text
Written byPhuoc Nguyen
Created
02 Sep, 2023
Category
Level 1 — Basic
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.js
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.js
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.js
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.
js
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 about front-end development? If so, feel free to create a new issue on GitHub using the button below. I'm happy to help with any topic you'd like to learn more about, even beyond what's covered in this post.
While I have a long list of upcoming topics, I'm always eager to prioritize your questions and ideas for future content. Let's learn and grow together! Sharing knowledge is the best way to elevate ourselves 🥷.
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