4

I'm trying to insert a marker at the beginning of a selection (that I use to position an element atop the selection).

I'm running into a weird case in Chrome where the selection is cleared when the range.insertNode line is executed:

$(document).on('mouseup', function (e) {
  var range = window.getSelection().getRangeAt(0).cloneRange();
  range.collapse(true);
  var markerElement = document.createElement("span");
  markerElement.appendChild(document.createTextNode("\ufeff"));
  // this will sometimes make the selection disappear in Chrome
  range.insertNode(markerElement);
  // make sure the marker is removed
  setTimeout(function(){
   markerElement.parentNode.removeChild(markerElement);
  }, 250);
});

Here is a jsbin example you can use to try it out: http://jsbin.com/agojib/1/edit

If you select a single letter, it will clear the selection. Any other selection will be fine.

Note: I'm using a modification of the code provided in How can I position an element next to user text selection?

Community
  • 1
  • 1
ZogStriP
  • 567
  • 1
  • 9
  • 25

1 Answers1

4

Ok, I think I got it: http://jsbin.com/agojib/7/edit

$(document).on('mouseup', function (e) {
  var range = window.getSelection().getRangeAt(0);
  // clone the current range
  var clone = range.cloneRange();
  range.collapse(true);
  var markerElement = document.createElement("span");
  markerElement.appendChild(document.createTextNode("\ufeff"));
  // insert the marker in the first range
  range.insertNode(markerElement);
  // retrieve the selection
  var selection = window.getSelection();
  // remove all the ranges
  selection.removeAllRanges();
  // add the previously cloned range
  selection.addRange(clone);
  // make sure the marker is removed
  setTimeout(function(){
   markerElement.parentNode.removeChild(markerElement);
  }, 250);
});

The solution is basically to clone the range, insert the marker inside the first range and use the cloned range to reselect previously selected text.

ZogStriP
  • 567
  • 1
  • 9
  • 25