Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent selecting text in Google Chrome?

Tags:

javascript

Doesn't oEvent.preventDefault(); work in GC? I need to prevent selecting text when the onmove event is triggered.

EDIT: It turns out to be very easy...

function disableSelection() {
   document.onselectstart = function() {return false;} // ie
   document.onmousedown = function() {return false;} // others
}
function enableSelection() {
   document.onselectstart = null; // ie
   document.onmousedown = null; // others
}

After that, there's no text selection triggered on the move event (ie. on the select event -- ie - indeed ie!)

like image 464
Frank Furd Avatar asked Feb 06 '10 08:02

Frank Furd


People also ask

How can I prevent text element selection with cursor drag?

To prevent text or element selection with cursor drag with JavaScript, we can use the window. getSelection(). removeAllRanges(); method in the selectstart event handler. document.

How do I stop chrome from highlighting things I click on?

It is pretty straightforward- go to accessibility settings and turn off the “Show a quick highlight on the focused object” option, and the features will be disabled for you. I hope you find this article useful.

How do I turn off text selection?

You can use the user-select property to disable text selection of an element. In web browsers, if you double-click on some text it will be selected/highlighted. This property can be used to prevent this.


2 Answers

-webkit-user-select: none CSS style controls whether the user is allowed to select the
text of the element.

For completeness sake, this covers all supporting browsers (IE is not considered a web browser):

.no-select
{
   user-select: none;
   -o-user-select:none;
   -moz-user-select: none;
   -khtml-user-select: none;
   -webkit-user-select: none;
}

To do it through Javascript, just create a class and add the node's attributes.

like image 152
LiraNuna Avatar answered Oct 20 '22 00:10

LiraNuna


To do it using JavaScript:

var el = document.getElementById("myElement"), s = el.style;
s.userSelect = "none";
s.webkitUserSelect = "none";
s.MozUserSelect = "none";
el.setAttribute("unselectable", "on"); // For IE and Opera

Note that for IE and Opera, the unselectable attribute isn't inherited by an element's children, so any child elements of el will also need unselectable to be set to "on".

like image 39
Tim Down Avatar answered Oct 20 '22 01:10

Tim Down