-
-
Save israelcrux/543e721be845c18d2f92652c0ebe06aa to your computer and use it in GitHub Desktop.
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 |
This saved my day, thank you so much!
Thanks, exactly what I was looking for
It is worth noting that currently getSelection() doesn't work on the content of <textarea> and elements in Firefox, Edge (Legacy) and Internet Explorer. HTMLInputElement.setSelectionRange() or the selectionStart and selectionEnd properties could be used to work around this.
MDN window.getSelection()
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 👏🏼
Thank you so much😂👍