Skip to content

Instantly share code, notes, and snippets.

@israelcrux
Last active January 14, 2024 13:58
Show Gist options
  • Save israelcrux/543e721be845c18d2f92652c0ebe06aa to your computer and use it in GitHub Desktop.
Save israelcrux/543e721be845c18d2f92652c0ebe06aa to your computer and use it in GitHub Desktop.
Save and Restore DOM text selection
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
@leshSimon
Copy link

leshSimon commented Mar 5, 2020

Thank you so much😂👍

@ganeshh123
Copy link

This saved my day, thank you so much!

@ramorgen
Copy link

Thanks, exactly what I was looking for

@swkidd
Copy link

swkidd commented May 15, 2020

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()

@sam0x17
Copy link

sam0x17 commented Mar 22, 2021

What is a good solution when the elements have been re-created by setting innerHTML?

@PlopTheReal
Copy link

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?

@danishiqbal4
Copy link

Life saver, You are awesome :-)

@shishirraven
Copy link

Thanks for sharing the script

@tchartron
Copy link

This is amazing thanks for sharing 👏🏼

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment