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:
- In many browsers
onselect
is fired only for input
or textarea
elements within a form
. That is a reason for the different HTML from yours.
- IE9 - 10 don't support
selectionDirection
, that's why IE's legacy event handling model is used also for these browsers.
- If not IE, you still can replace a bunch of text by selecting it with mouse and hitting a key without releasing the mouse button. I suppose this could be prevented by detecting if the mouse button is down, and in that case preventing keyboard actions. This would be your homework ; ).
- The code for IE works with contenteditable
div
s too.
EDIT
Looks like I've done your "homework" too.