Reputation: 1437
Is there way to create a content-editable div where users can't select/highlight content but can still input things? I want to create an interface where users are forced to delete and enter things key-by-key, without being able to make mass edits via highlighting.
I've looked into the various forms of the "user-select" property in CSS, which works for static content, but doesn't seem to work for content-editable elements/inputs.
Any ideas?
Thanks
Upvotes: 5
Views: 3928
Reputation: 1067
I know you want to disable mass deleting, but if others are wanting to not show a highlight color (which would be user-select: none
for other elements), you can put the following in your css:
::selection { background: transparent }
This will make the selection look like user-select: none
but it will still allow mass deleting. But it could make users think there is no selection, so they possibly won't mass delete.
Hope this works for you, but mainly towards others.
Upvotes: 1
Reputation: 23416
If you can accept a textarea
instead of a contenteditable div
, you can do something like this:
window.onload = function () {
var div = document.getElementById('div');
if (div.attachEvent) {
div.attachEvent('onselectstart', function (e) {
e.returnValue = false;
return false;
});
div.attachEvent('onpaste', function (e) {
e.returnValue = false;
return false;
});
} else {
div.addEventListener('paste', function (e) {
e.preventDefault();
});
div.addEventListener('select', function (e) {
var start = this.selectionStart,
end = this.selectionEnd;
if (this.selectionDirection === 'forward') {
this.setSelectionRange(end, end);
} else {
this.setSelectionRange(start, start);
}
});
}
};
HTML:
<form>
<textarea id="div"></textarea>
</form>
Some observations on the code:
onselect
is fired only for input
or textarea
elements within a form
. That is a reason for the different HTML from yours.selectionDirection
, that's why IE's legacy event handling model is used also for these browsers.div
s too.EDIT
Looks like I've done your "homework" too.
Upvotes: 1