Methods to Disable Text Selection on A Web Page Using HTML jQuery & CSS

At times we need to disable text selection on web pages using HTML, jQuery and CSS. We have shown examples below so that it could be very clear how we could disable text selection by adding a small code snippet on HTML, jQuery or CSS web page and we could easily get the job done. So after reading the post you would be able to do that by just adding the code piece.

There is one thing we need to keep in mind in HTML in order to disable the text selection we have to choose user-select property value as none in the first place.

First we will use jQuery method that requires adding the unselectable attribute to your DOM Element.

Disable text selection on a web page using HTML/CSS

User-selected non value is totally supported in Chrome, Opera and other browsers. We will have shown below most of them. This is the best way to do it while using CSS:

<!DOCTYPE html>
<html>
<head>
   <title>How to disable text selection on a web page</title>
   <style type="text/css">
        body{
            user-select: none; /* supported by Chrome and Opera */
            -webkit-user-select: none; /* Safari */
            -khtml-user-select: none; /* Konqueror HTML */
            -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* Internet Explorer/Edge */
        }
   </style>
</head>
</html>

Method to disable the text selection using JQuery

Now we will show the example of how we can disable text selection with the help of using jQuery. Check the example below.

<!DOCTYPE html>
<html>
<head>
   <title>Disable the text selection using JQuery</title>
   <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
   
<script type="text/javascript">
    (function($){
        $.fn.disableSelection = function() {
            return this
                     .attr('unselectable', 'on')
                     .css('user-select', 'none')
                     .on('selectstart', false);
                             };
    })(jQuery);
    
    $('body').disableSelection();
</script>
   
</body>
</html>

Disable Text Selection Using jQuery Ui

Here is how we can easily disable text selection on any HTML web page with the help of jquery ui. In this example we have shown we can use jQuery UI to disable the text selection as we have portrayed them previously. The code snippet below shows the script that you can copy and try it.

<!DOCTYPE html>
<html>
<head>
   <title>disable text selection using jQuery ui on any web page</title>
   <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
   <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
   
<h3>Here is the script that we can use</h3>
   
   <script type="text/javascript">
    $('body').disableSelection();
</script>
   
</body>
</html>