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
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>
A live demo at jsFiddle.
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.divs too.EDIT
Looks like I've done your "homework" too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With