Inserting an item into a range deselects in Chrome

I am trying to insert a marker at the beginning of the selection (which I use to place an element on top of the selection).

I got confused in a strange case in Chrome where the selection is cleared when the range.insertNode line is range.insertNode :

 $(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 that you can use to try: http://jsbin.com/agojib/1/edit

If you select single , it will clear the selection. Any other choice would be ok.

Note: I am using a modification of the code presented in How to place an item next to user text selection?

+4
source share
1 answer

Ok, I think I get 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 a range, insert a marker in the first range, and use the cloned range to reselect previously selected text.

+4
source

All Articles