In most browsers, this can be achieved using proprietary variations on the CSS user-select
property, originally proposed and then abandoned in CSS 3 and now proposed in CSS UI Level 4:
*.unselectable {
-moz-user-select: none;
-khtml-user-select: none;
-webkit-user-select: none;
/*
Introduced in Internet Explorer 10.
See http://ie.microsoft.com/testdrive/HTML5/msUserSelect/
*/
-ms-user-select: none;
user-select: none;
}
For Internet Explorer < 10 and Opera < 15, 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"));
Update 30 April 2014: This tree traversal needs to be rerun whenever a new element is added to the tree, but it seems from a comment by @Han that it is possible to avoid this by adding a mousedown
event handler that sets unselectable
on the target of the event. See http://jsbin.com/yagekiji/1 for details.
This still doesn't cover all possibilities. While it is impossible to initiate selections in unselectable elements, in some browsers (Internet Explorer and Firefox, for example) it's still impossible to prevent selections that start before and end after the unselectable element without making the whole document unselectable.