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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *