Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent text selection/highlighting in a content editable div

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

like image 847
Eugene Avatar asked Nov 02 '22 14:11

Eugene


1 Answers

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 divs too.

EDIT

Looks like I've done your "homework" too.

like image 121
Teemu Avatar answered Nov 15 '22 06:11

Teemu