How to disable text selection through jQuery?

I know this question has already been asked ( here ), but all the answers that I found relate to the css selector: choice (which is not yet widely supported by browsers).

So, how can I turn off text selection on my html page via jQuery without relying on css tricks?

+6
source share
4 answers

Here is a simple single line to disable text selection throughout the page. (do you need or not another question)

$(document).bind('selectstart dragstart', function(e) { e.preventDefault(); return false; }); 
+13
source

If you want to avoid plugins, you can extract the relevant parts from the jQuery user interface 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(); 
+12
source

Enable the jQuery user interface and use $(element).disableSelection() .

However, disabling text selection is a very unfriendly user if it is not used in a context where random choices are likely (for example, Drag & Drop or buttons where users can double-click to make several changes faster (for example, in spinners))

+4
source

Source: https://habr.com/ru/post/898768/


All Articles