Categories
JavaScript Answers

How to Disable Text Selection with JavaScript?

Spread the love

Sometimes, we want to disable text selection with JavaScript.

In this article, we’ll look at how to disable text selection with JavaScript.

Disable Text Selection with JavaScript

To disable text selection with JavaScript, we can set the onselectstart and onmousedown properties of the element we want to disable selection for to a function that returns false .

For instance, if we have the following HTML:

<div>  
  hello world  
</div>

Then we write:

const disableselect = (e) => {  
  return false  
}  
document.onselectstart = disableselect  
document.onmousedown = disableselect

to disable select on the whole page.

We create the disableselect function that returns false and set that as the value of the document.onselectstart and document.onmousedown properties to disable text selection on the whole page.

Now when we try to select the text, nothing will happen.

Conclusion

To disable text selection with JavaScript, we can set the onselectstart and onmousedown properties of the element we want to disable selection for to a function that returns false .

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 *