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 .