Disabling Text Selection with jQuery

In practice I often need this functionality — not to stop copy-pasters (since it's trivially bypassed by disabling JavaScript), but for projects with sliders, custom scrollbars, and drag & drop interfaces, where mouse events cause unwanted text selection.

Here are two jQuery extension methods I use regularly:

jQuery.fn.extend({
    disableSelection: function() {
        this.each(function() {
            this.onselectstart = function() { return false; };
            this.unselectable = "on";
            jQuery(this).css('-moz-user-select', 'none');
        });
    },
    enableSelection: function() {
        this.each(function() {
            this.onselectstart = function() {};
            this.unselectable = "off";
            jQuery(this).css('-moz-user-select', 'auto');
        });
    }
});

// Cross-browser call
$(document).ready(function() {
    $('body *').disableSelection();
});

Note: Use $('body *') as the selector for full cross-browser compatibility — simply $('body') or $(document) does not work in Opera.

  • disableSelection — disables text selection
  • enableSelection — re-enables text selection

Nothing groundbreaking here, just a handy pair of functions I always end up searching for, so I wanted to share them.