Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent selection in HTML

I have a div on a HTML page and whenever I press the mouse and move it, it will show that "can't drop" cursor like it selects something. Is there a way to disable selection? I tried CSS user-select with none without success.

like image 875
Tower Avatar asked Feb 24 '10 12:02

Tower


People also ask

How do you stop a selection in HTML?

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.

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.


1 Answers

The proprietary variations of user-select will work in most modern browsers:

*.unselectable {    -moz-user-select: -moz-none;    -khtml-user-select: none;    -webkit-user-select: none;     /*      Introduced in IE 10.      See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/    */    -ms-user-select: none;    user-select: none; } 

For IE < 10 and Opera, you will need to use the unselectable attribute of the element you wish to be unselectable. You can set this using an attribute in HTML:

<div id="foo" unselectable="on" class="unselectable">...</div> 

Sadly this property isn't inherited, meaning you have to put an attribute in the start tag of every element inside the <div>. If this is a problem, you could instead use JavaScript to do this recursively for an element's descendants:

function makeUnselectable(node) {     if (node.nodeType == 1) {         node.setAttribute("unselectable", "on");     }     var child = node.firstChild;     while (child) {         makeUnselectable(child);         child = child.nextSibling;     } }  makeUnselectable(document.getElementById("foo")); 
like image 142
Tim Down Avatar answered Oct 10 '22 23:10

Tim Down