Disable Text Selection Using JavaScript

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.

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.

How to Change Image on Hover with JavaScript How to Disable Button by Class Name in JavaScript How To Change Image Size with JavaScript How to change Image opacity with JavaScript How to Change image src on click with JavaScript How to get the lang attribute value in JavaScript How to Get attribute Value using JavaScript How To Check if Attribute Exists or not with JavaScript How To Count number of links on Page with JavaScript How To Scroll Page to Bottom using JavaScript How To Detect Shift Key Press with JavaScript Change Text Color On Hover with JavaScript Hide and Show div using JavaScript Get Button text with JavaScript Get textarea value with JavaScript Get table row Height with JavaScript Auto Increase width of input field with JavaScript Set Textarea maxLength with JavaScript Set Textarea Value with JavaScript JavaScript Count list items JavaScript set input field value Count Button Clicks with JavaScript Scroll Page to the Top on Click with JavaScript Change id of Element with JavaScript JavaScript Change li Text Color