How to disable text selection via jQuery?

10,963

Solution 1

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

Solution 2

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;
});

Solution 3

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();

Solution 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))

Share:
10,963

Related videos on Youtube

Peter Burns
Author by

Peter Burns

Stack Overflow Valued Associate #00001 Wondering how our software development process works? Take a look! Find me on twitter, or read my blog. Don't say I didn't warn you because I totally did. However, I no longer work at Stack Exchange, Inc. I'll miss you all. Well, some of you, anyway. :)

Updated on June 04, 2022

Comments

  • Peter Burns
    Peter Burns about 2 years

    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?

  • Admin
    Admin over 12 years
    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)
  • Admin
    Admin over 12 years
    It seems cross-browser enough, thnx!
  • Dominique
    Dominique about 11 years
    Thanks! Simple, elegant solution.
  • Gary
    Gary almost 11 years
    This was a good solution, but unfortunately $.browser has been removed as of 1.9 so this will fail.
  • zero298
    zero298 over 10 years
    Thanks, even works with jQuery-UI if you remove the dragstart
  • Legionar
    Legionar almost 9 years
    The link is broken... And also this is not correct solution - Halfhoof's is correct and should be accepted.