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?

4 Answers 4

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;
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Simple, elegant solution.
Thanks, even works with jQuery-UI if you remove the dragstart
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();

Comments

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

1 Comment

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

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

3 Comments

It seems cross-browser enough, thnx!
This was a good solution, but unfortunately $.browser has been removed as of 1.9 so this will fail.
The link is broken... And also this is not correct solution - Halfhoof's is correct and should be accepted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.