Categories
JavaScript Answers

How to prevent text or element selection with cursor drag with JavaScript?

Spread the love

Sometimes, we want to prevent text or element selection with cursor drag with JavaScript.

In this article, we’ll look at how to prevent text or element selection with cursor drag with JavaScript.

How to prevent text or element selection with cursor drag with JavaScript?

To prevent text or element selection with cursor drag with JavaScript, we can use the window.getSelection().removeAllRanges(); method in the selectstart event handler.

For instance, we write

document.onselectstart = () => {
  window.getSelection().removeAllRanges();
};

to set document.onselectstart to a function that calls window.getSelection().removeAllRanges(); to remove all selection in the document when we start making selections.

This will prevent anything from being selected on the page.

Conclusion

To prevent text or element selection with cursor drag with JavaScript, we can use the window.getSelection().removeAllRanges(); method in the selectstart event handler.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.