How to disable text selection via jQuery?
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))
Related videos on Youtube
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, 2022Comments
-
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 over 12 yearsall 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 over 12 yearsIt seems cross-browser enough, thnx!
-
Dominique about 11 yearsThanks! Simple, elegant solution.
-
Gary almost 11 yearsThis was a good solution, but unfortunately
$.browser
has been removed as of 1.9 so this will fail. -
zero298 over 10 yearsThanks, even works with jQuery-UI if you remove the
dragstart
-
Legionar almost 9 yearsThe link is broken... And also this is not correct solution - Halfhoof's is correct and should be accepted.