If you're open to using a textarea
instead of a contenteditable div
, you can achieve the desired functionality with the following code:
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>
Check out the live demo on jsFiddle.
Some key points regarding the code:
- In certain browsers,
onselect
is only triggered for input
or textarea
elements within a form
. This explains the HTML structure used in the example.
- IE9 - 10 do not support
selectionDirection
, hence the use of IE's legacy event handling model for these browsers as well.
- In non-IE browsers, there is a potential issue where selected text can be quickly replaced by hitting a key while holding down the mouse button. Preventing keyboard actions when the mouse button is pressed could address this behavior.
- The code designed for IE also works with contenteditable
div
elements.
EDIT
I have also addressed the additional challenge mentioned in your question in another updated jsFiddle.