We've got a project, were we disabling text selection to all body content. So the solution for this is CSS styles for normal browsers (like user-select: none
) and workaround for IE (like document.body.onselectstart = function () { return false; }
).
So the problem is: how to enable text selection in some div-elements in IE? And how to do it simple and quickly?
We've got a project, were we disabling text selection to all body content. So the solution for this is CSS styles for normal browsers (like user-select: none
) and workaround for IE (like document.body.onselectstart = function () { return false; }
).
So the problem is: how to enable text selection in some div-elements in IE? And how to do it simple and quickly?
Share Improve this question asked Jan 28, 2013 at 6:58 verkholantsevverkholantsev 1053 silver badges8 bronze badges 1- Can't those div's properties be overridden from the start? – Isaias Commented Jan 28, 2013 at 7:08
4 Answers
Reset to default 3Well, the easiest way would be to reverse your logic and only apply this rule to elements that aren't supposed to be able to have their text selected. Problem with applying this rule to the whole body is that any child elements then already receive this overridden event from their parent (body) element, and the way to re-initialize onselectstart
event isn't as easy as some seem to have assumed with their answers here. In your case, I would remove this rule for the whole body and then only apply it to the individual elements that don't have any children where the overriding rule must not apply.
Example:
<body>
this is some text that is selectable
<div style='-o-user-select: none;
-webkit-user-select: none;
-moz-user-select: -moz-none;
-khtml-user-select: none;
-ms-user-select: none;
user-select: none;'
onselectstart='return false;'
unselectable='on'>
this is some text that's not selectable
</div>
</body>
> see working demo on JSFiddle
Note that some individual properties listed aren't supported yet and I've added them anyway for future-proofing purposes. The rule-set is piled in a way to support as many different browsers as possible. Some will obey CSS styling, some need a JavaScript hack (IE < 10) and Opera browsers obey to a special element property (see below).
EDIT: Added support for Opera browsers (unselectable='on'
)
<div onselectstart='return true;'>blablabla</div>
document.body.onselectstart = function (event) {
if(event.srcElement.parentNode.id == 'mydiv')//you may need to loop if the parentNode is
{ //not a div element
return true;
}
else{
return false;
}
}
note: disabling javascript will enable the user to select text
I have updated the fiddle link
use jQuery
$("body").disableSelection();