In this tutorial we will see how to Disable Text Selection Using JavaScript. The .preventDefault() method is used with onselectstart property to do this task.
Table of Contents
HTML Code
HTML Code is given below, This code contains the heading h2 element with the text inside.
<!DOCTYPE html>
<html>
<head>
<title>Disable the Text Selection using JavaScript</title>
</head>
<body>
<h2>Try to Select Me</h2>
</body>
</html>
.preventDefault() method
The preventDefault() method prevents the browser from executing the default action of the selected HTML element. In this example it will stop the selection of the text.
onselectstart property
The onselectstart property is an event handler that triggers when the element or it's content is being selected.
JavaScript Code
In this example the onselectstart property will trigger a function which contain the preventDefault() method. The preventDefault() method will stop the selection of the text inside the whole document.
After that alert message is displayed. You can use this exact code for individual elements like paragraph tags or heading tags, instead of using with the document query selector.
Take a look at the code given below.
<script>
document.onselectstart = () => {
event.preventDefault();
alert('Sorry!');
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Disable Text Selection Using JavaScript.