Suhail Gupta
Suhail Gupta

Reputation: 23246

Disable text selection in contenteditable = true div

I am trying to disable text selection inside a contenteditable=true div.

The div with id d looks as follows:

<div contenteditable="true" id="d" class="noselect"> 

</div>

<p id="log"></p>

I applied the noselect class to disable text selection which looks like:

 .noselect {
    -webkit-touch-callout: none; /* iOS Safari */
        -webkit-user-select: none; /* Safari */
        -khtml-user-select: none; /* Konqueror HTML */
        -moz-user-select: none; /* Firefox */
            -ms-user-select: none; /* Internet Explorer/Edge */
                user-select: none; /* Non-prefixed version, currently
                                    supported by Chrome and Opera */
}

But this does not seem to work. I can still do ctrl+a , or drag and select all the text. How could I disable the selection?

Here is also the fiddle for it : https://jsfiddle.net/hpeLqmyg/1/

Upvotes: 2

Views: 1286

Answers (3)

Shubham Sharma
Shubham Sharma

Reputation: 435

A simple solution would be to use the selectstart event.

const contentEditableDiv = document.querySelector('#divId');
contentEditableDiv.addEventListener('selectstart' , event=> event.preventDefault());

MDN Docs

Upvotes: 0

Helena Vasconcelos
Helena Vasconcelos

Reputation: 1

I had the same question and found below to be the simplest solution:

$("#d").on('click', function() {
    let selection = window.getSelection().getRangeAt(0)
    if (selection.startOffset !== selection.endOffset) {
      window.getSelection().removeAllRanges();
    }
});

Upvotes: 0

You can mimic the inability to use selection by setting "selection" pseudo-element:

.noselect::selection {
    background: transparent;
    color: //noselect's color;
}

To actually disable selection functionality you can listen to "click" event and check if your element has selection. If it does then cancel it:

const noselect = document.getElementById('d');

const setCaret = (target, position = 0) => {
    const range = document.createRange();
    const sel = window.getSelection();
    range.setStart(target.childNodes[0], position);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
};

noselect.addEventListener('click', (e) => {
    const range = window.getSelection().getRangeAt(0);
    const { startOffset, endOffset } = range;
    if (endOffset - startOffset > 1) {
        setCaret(noselect, endOffset);
    }
});

Upvotes: 1

Related Questions