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

Estimated read time 1 min read

To prevent text or element selection with cursor drag in JavaScript, you can use the user-select CSS property. Here’s an example:

.no-select {
  -webkit-user-select: none; /* Safari */
  -moz-user-select: none; /* Firefox */
  -ms-user-select: none; /* Internet Explorer/Edge */
  user-select: none; /* Standard */

<div class="no-select">This text cannot be selected with cursor drag</div>

In this example, the CSS class no-select sets the user-select property to none, which disables text selection with cursor drag. You can apply this class to any HTML element you want to prevent from being selected.

Note that different browsers have different vendor prefixes for the user-select property, so it’s best to include all of them in your CSS to ensure cross-browser compatibility.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply