Eugene
Eugene

Reputation: 1437

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

Upvotes: 5

Views: 3928

Answers (2)

Cameron
Cameron

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

Teemu
Teemu

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>

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.

Upvotes: 1

Related Questions