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?