Sacha
Sacha

Reputation: 893

How to cancel selection in contenteditable div?

On my page, I have a contenteditable div element. When a specific key is pressed, a function executes:

function bla(element) {
  if (getSelectionHtml() != "") {
    replaceSelectedText("text");
  }
}

getSelectionHtml() checks if something is selected by the user. replaceSelectedText(text) replaces the selected text with a given string. Both functions are working properly.
After the selected text has been replaced, I want to 'cancel' the user's selection, as the selection is now equal to the 'new' string, so just deleting the text is not an option.

I tried this:

element.style.userSelect = "none";
element.style.userSelect = "text;

But it didn't work because userSelect: none doesn't seem to change anything in a div element with contenteditable. Also, this solution looks pretty ugly for such a simple problem.

So, how can I cancel the user's selection?

Upvotes: 1

Views: 782

Answers (1)

Akansh
Akansh

Reputation: 1785

I think you want to remove selection completely. You can do so once you have replaced the string with

window.getSelection().removeAllRanges()

So basically, once you select the range of content, you can get the range with window.getSelection() method which returns set of details about selected content. It has many functions to alter the range and remove the range completely. To know more, you can read in brief of all supported methods Selection API

Upvotes: 2

Related Questions