Last active
January 14, 2024 13:58
-
-
Save israelcrux/543e721be845c18d2f92652c0ebe06aa to your computer and use it in GitHub Desktop.
Save and Restore DOM text selection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function saveSelection() { | |
if (window.getSelection) { | |
var sel = window.getSelection(); | |
if (sel.getRangeAt && sel.rangeCount) { | |
return sel.getRangeAt(0); | |
} | |
} else if (document.selection && document.selection.createRange) { | |
return document.selection.createRange(); | |
} | |
return null; | |
} | |
function restoreSelection(range) { | |
if (range) { | |
if (window.getSelection) { | |
var sel = window.getSelection(); | |
sel.removeAllRanges(); | |
sel.addRange(range); | |
} else if (document.selection && range.select) { | |
range.select(); | |
} | |
} | |
} | |
/** | |
* How to use: | |
* You have a text editor, or a textarea, or any text element, then you want to create a widget | |
* that adds a link, or anything that causes a new element to get focus so your text element looses it and | |
* selection is lost, then you may want to restore that selection after. | |
*/ | |
var selectionRange = saveSelection(); | |
// then, you loose focus | |
/** | |
* You get what you wanted and you want your selection back there | |
*/ | |
restoreSelection(selectionRange); | |
// Credits: Tim Down's SO answer http://stackoverflow.com/a/3316483/1470564 |
swkidd
commented
May 15, 2020
What is a good solution when the elements have been re-created by setting innerHTML?
With React it seems to not work when the component get rerendered, llike it's loosing track of the selection when rerendering.
It may be more a general react question... Anyone got an idea regarding this behavior?
Life saver, You are awesome :-)
Thanks for sharing the script
This is amazing thanks for sharing 👏🏼
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment