6

I know this question have been already asked (here), but all the answers I've found dealt with css selector :selection (that is not yet too widely supported by browsers).

So, how can I disable text selection on my html page via jQuery, not relying on css tricks?

Community
  • 1
  • 1

4 Answers4

14

Here is a simple one-liner to disable selecting text on your whole page. (whether you should or not is another question)

$(document).bind('selectstart dragstart', function(e) {
  e.preventDefault();
  return false;
});
Legionar
  • 7,472
  • 2
  • 41
  • 70
Halfhoot
  • 310
  • 3
  • 10
12

If you want to avoid plugins, you can extract the relevant parts from the jQuery UI source:

/*!
 * jQuery UI 1.8.16
 *
 * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
$.support.selectstart = "onselectstart" in document.createElement("div");
$.fn.disableSelection = function() {
    return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) +
        ".ui-disableSelection", function( event ) {
        event.preventDefault();
    });
};

$("#somediv").disableSelection();
Dennis
  • 32,200
  • 11
  • 64
  • 79
4

Include jQuery UI and use $(element).disableSelection().

However, disabling text selection is very user-unfriendly unless used in a context where accidental selections are likely (e.g. Drag&Drop or buttons where users are likely to doubleclick to perform multiple changes faster (e.g. in spinners))

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • all right, but I'd prefer not to add any plugins because I'm operating on 3-rd party website that has only jquery plugged in (injecting my small javascript snippet) –  Oct 06 '11 at 14:08
-2

Try that http://code.jdempster.com/jQuery.DisableTextSelect/jquery.disable.text.select.js

KodeFor.Me
  • 13,069
  • 27
  • 98
  • 166