How to Disable Text Selection Using Javascript or CSS

In this tutorial, you will learn how to disable text selection using javascript or css.  Most of the times it is done to protect content from being copied. In web development world, we have 2 simplest methods to achieve this.  One is using javascript and another one is using CSS.

Javascript approach will fail if user has disabled javascript in his browser.  CSS approach is evergreen and it will work no matter what without any issue.  So CSS is my recommended way of approach to achieve something like this. But just for the sake of learning purpose, I have shown both the methods in the video. HTML, Javascript and CSS code is given below.

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    
    <div>
        
        <p class="unselectable">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quidem, voluptate quia nam exercitationem perspiciatis pariatur numquam atque illo vero eius dolor iure nemo modi, et inventore cupiditate in quibusdam. Quidem.</p>

        <p id="test">Lorem ipsum dolor sit amet consectetur, adipisicing elit. Quidem, voluptate quia nam exercitationem perspiciatis pariatur numquam atque illo vero eius dolor iure nemo modi, et inventore cupiditate in quibusdam. Quidem.</p>
    </div>
    <script src="script.js"></script>
</body>
</html>

Javascript:

document.querySelector('#test').addEventListener('selectstart', (e) => {
    e.preventDefault();
})

CSS:

div {
    text-align: center;
}

p {
    width: 50%;
    display: inline-block;
    padding: 10px;
    border: 1px solid black;
}

.unselectable {
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }

 

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •