[javascript] How to disable text selection using jQuery?

Does jQuery or jQuery-UI have any functionality to disable text selection for given document elements?

This question is related to javascript jquery jquery-ui

The answer is


This can easily be done using JavaScript This is applicable to all Browsers

<script type="text/javascript">

/***********************************************
* Disable Text Selection script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE 
    target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
    target.style.MozUserSelect="none"
else //All other route (For Opera)
    target.onmousedown=function(){return false}
target.style.cursor = "default"
}
 </script>

Call to this function

<script type="text/javascript">
   disableSelection(document.body)
</script>

Here's a more comprehensive solution to the disconnect selection, and the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)

(function($){

  $.fn.ctrlCmd = function(key) {

    var allowDefault = true;

    if (!$.isArray(key)) {
       key = [key];
    }

    return this.keydown(function(e) {
        for (var i = 0, l = key.length; i < l; i++) {
            if(e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                allowDefault = false;
            }
        };
        return allowDefault;
    });
};


$.fn.disableSelection = function() {

    this.ctrlCmd(['a', 'c']);

    return this.attr('unselectable', 'on')
               .css({'-moz-user-select':'-moz-none',
                     '-moz-user-select':'none',
                     '-o-user-select':'none',
                     '-khtml-user-select':'none',
                     '-webkit-user-select':'none',
                     '-ms-user-select':'none',
                     'user-select':'none'})
               .bind('selectstart', false);
};

})(jQuery);

and call example:

$(':not(input,select,textarea)').disableSelection();

jsfiddle.net/JBxnQ/

This could be also not enough for old versions of FireFox (I can't tell which). If all this does not work, add the following:

.on('mousedown', false)

If you use jQuery UI, there is a method for that, but it can only handle mouse selection (i.e. CTRL+A is still working):

$('.your-element').disableSelection(); // deprecated in jQuery UI 1.9

The code is realy simple, if you don't want to use jQuery UI :

$(el).attr('unselectable','on')
     .css({'-moz-user-select':'-moz-none',
           '-moz-user-select':'none',
           '-o-user-select':'none',
           '-khtml-user-select':'none', /* you could also put this in a class */
           '-webkit-user-select':'none',/* and add the CSS class here instead */
           '-ms-user-select':'none',
           'user-select':'none'
     }).bind('selectstart', function(){ return false; });

One solution to this, for appropriate cases, is to use a <button> for the text that you don't want to be selectable. If you are binding to the click event on some text block, and don't want that text to be selectable, changing it to be a button will improve the semantics and also prevent the text being selected.

<button>Text Here</button>

1 line solution for CHROME:

body.style.webkitUserSelect = "none";

and FF:

body.style.MozUserSelect = "none";

IE requires setting the "unselectable" attribute (details on bottom).

I tested this in Chrome and it works. This property is inherited so setting it on the body element will disable selection in your entire document.

Details here: http://help.dottoro.com/ljrlukea.php

If you're using Closure, just call this function:

goog.style.setUnselectable(myElement, true);

It handles all browsers transparently.

The non-IE browsers are handled like this:

goog.style.unselectableStyle_ =
    goog.userAgent.GECKO ? 'MozUserSelect' :
    goog.userAgent.WEBKIT ? 'WebkitUserSelect' :
    null;

Defined here: http://closure-library.googlecode.com/svn/!svn/bc/4/trunk/closure/goog/docs/closure_goog_style_style.js.source.html

The IE portion is handled like this:

if (goog.userAgent.IE || goog.userAgent.OPERA) {
// Toggle the 'unselectable' attribute on the element and its descendants.
var value = unselectable ? 'on' : '';
el.setAttribute('unselectable', value);
if (descendants) {
  for (var i = 0, descendant; descendant = descendants[i]; i++) {
    descendant.setAttribute('unselectable', value);
  }
}

The following would disable the selection of all classes 'item' in all common browsers (IE, Chrome, Mozilla, Opera and Safari):

$(".item")
        .attr('unselectable', 'on')
        .css({
            'user-select': 'none',
            'MozUserSelect': 'none'
        })
        .on('selectstart', false)
        .on('mousedown', false);

I think this code works on all browsers and requires the least overhead. It's really a hybrid of all the above answers. Let me know if you find a bug!

Add CSS:

.no_select { user-select: none; -o-user-select: none; -moz-user-select: none; -khtml-user-select: none; -webkit-user-select: none; -ms-user-select:none;}

Add jQuery:

(function($){
    $.fn.disableSelection = function() 
    {       
        $(this).addClass('no_select');              
        if($.browser.msie)
        {
            $(this).attr('unselectable', 'on').on('selectstart', false);            
        }
    return this;            
};
})(jQuery);

Optional: To disable selection for all children elements as well, you can change the IE block to:

$(this).each(function() {
    $(this).attr('unselectable','on')
    .bind('selectstart',function(){ return false; });
});

Usage:

$('.someclasshere').disableSelection();

        $(document).ready(function(){
            $("body").css("-webkit-user-select","none");
            $("body").css("-moz-user-select","none");
            $("body").css("-ms-user-select","none");
            $("body").css("-o-user-select","none");
            $("body").css("user-select","none");
        });

I've tried all the approaches, and this one is the simplest for me because I'm using IWebBrowser2 and don't have 10 browsers to contend with:

document.onselectstart = new Function('return false;');

Works perfectly for me!


Best and simplest way I found it, prevents ctrl + c, right click. In this case I blocked everything, so I don't have to specify anything.

$(document).bind("contextmenu cut copy",function(e){
    e.preventDefault();
    //alert('Copying is not allowed');
});

This is actually very simple. To disable text selection (and also click+drag-ing text (e.g a link in Chrome)), just use the following jQuery code:

$('body, html').mousedown(function(event) {
    event.preventDefault();
});

All this does is prevent the default from happening when you click with your mouse (mousedown()) in the body and html tags. You can very easily change the element just by changing the text in-between the two quotes (e.g change $('body, html') to $('#myUnselectableDiv') to make the myUnselectableDiv div to be, well, unselectable.

A quick snippet to show/prove this to you:

_x000D_
_x000D_
$('#no-select').mousedown(function(event) {_x000D_
  event.preventDefault();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span id="no-select">I bet you can't select this text, or drag <a href="#">this link</a>, </span>_x000D_
<br/><span>but that you can select this text, and drag <a href="#">this link</a>!</span>
_x000D_
_x000D_
_x000D_

Please note that this effect is not perfect, and performs the best while making the whole window not selectable. You might also want to add

the cancellation of some of the hot keys (such as Ctrl+a and Ctrl+c. Test: Cmd+a and Cmd+c)

as well, by using that section of Vladimir's answer above. (get to his post here)


I found this answer ( Prevent Highlight of Text Table ) most helpful, and perhaps it can be combined with another way of providing IE compatibility.

#yourTable
{
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  user-select: none;
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-ui

How to auto adjust the div size for all mobile / tablet display formats? jQuery not working with IE 11 JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined Best Practice to Organize Javascript Library & CSS Folder Structure Change table header color using bootstrap How to get HTML 5 input type="date" working in Firefox and/or IE 10 Form Submit jQuery does not work Disable future dates after today in Jquery Ui Datepicker How to Set Active Tab in jQuery Ui How to use source: function()... and AJAX in JQuery UI autocomplete