Skip to content

Instantly share code, notes, and snippets.

@Fedia
Created September 10, 2016 22:10
Show Gist options
  • Save Fedia/2c3512a9a5ce171fc25b635370785803 to your computer and use it in GitHub Desktop.
Save Fedia/2c3512a9a5ce171fc25b635370785803 to your computer and use it in GitHub Desktop.
/**
* Refactored
* http://stackoverflow.com/questions/17678843/cant-restore-selection-after-html-modify-even-if-its-the-same-html
*/
function saveSelection(el) {
var win = el.ownerDocument.defaultView;
var range = win.getSelection().getRangeAt(0);
var prefixRange = range.cloneRange();
prefixRange.selectNodeContents(el);
prefixRange.setEnd(range.startContainer, range.startOffset);
var start = prefixRange.toString().length;
return {
start: start,
end: start + range.toString().length
};
}
function restoreSelection(el, saved) {
var doc = el.ownerDocument;
var win = doc.defaultView;
var range = doc.createRange();
range.setStart(el, 0);
range.collapse(true);
var iter = doc.createNodeIterator(el, NodeFilter.SHOW_TEXT);
var node;
var i = 0, j = 0;
var started = false;
while (node = iter.nextNode()) {
j = i + node.length;
if (!started && saved.start >= i && saved.start <= j) {
range.setStart(node, saved.start - i);
started = true;
}
if (started && saved.end >= i && saved.end <= j) {
range.setEnd(node, saved.end - i);
break;
}
i = j;
}
var sel = win.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment