Skip to content
Advertisement

Moving caret to the end in a content editable div not working in IE11

I implemented a process where the user selects an option from a div, and it is inserted in the content editable div.

To achieve that, first I save the selection range on the mouseup and keyup events of the editable div.

When the user clicks on one of the options of the div, it restores the selection range, inserts the text in the position saved and moves the caret at the end of the inserted text. Also, I save the new caret position again, just in case the user clicks on another option, inserting a new text next to the one added before.

It works fine in all browsers except in IE11. When the user clicks more than 1 time to the div to insert a text, the first value is replaced for the new one, instead of being inserted after the first inserted text.

It seems the selection.collapseToEnd() does not work quite well in IE11.

If someone knows a nice way to fix that, it will be very helpful.

Thank you.

JSFiddle: https://jsfiddle.net/7k1rt82s/4/

The code:

HTML

<div id="insert-text-div" style="border-style: solid; width: 100px;cursor: pointer;">Option DIV</div>
<div id="editor" contenteditable="true" style="border-style: solid; height: 150px;">Please click on the option div to add a dummy text.</div>

JS

var selectedRange;

$( "#editor" ).on('mouseup keyup', function() {
  // Save selection
  var selection = window.getSelection();
    if (selection.getRangeAt && selection.rangeCount) {
        selectedRange = selection.getRangeAt(0);
    }
});

$('#insert-text-div').on('click', function() {
  if (!selectedRange) return;

  // Get the current selection and set the selection range stored in the Editor mouseup / keyup event
  var selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(selectedRange);

  // Insert the text into the range
  var range = selection.getRangeAt(0);
  range.deleteContents();
  var textNode = document.createTextNode("DummyText");
  range.insertNode(textNode);

  // Move the caret to the end of the added text
  selection.collapseToEnd();
  // Save the selection in case the user immediately inserts another text
  $('#editor').trigger('keyup');
});

Advertisement

Answer

I found the table of compatibility from MDN, which is a resource recommended. There it is mentioned that the compatibility of the collapseToEnd function is unknown for Internet Explorer.

https://developer.mozilla.org/en-US/docs/Web/API/Selection/collapseToEnd .

Furthermore, the issue may come from of range of null and you may look deeper in comments.

https://w3c.github.io/selection-api/#background Note See bug 15470. IE9, Firefox 12.0a1, Chrome 17 dev, and Opera Next 12.00 alpha all make the range initially null.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement