Forked from israelcrux/save-and-restore-contenteditable-selection.js
Created
April 19, 2019 03:27
-
-
Save sonnh58/290f11a8b88b4246e17ea62b438cb9e7 to your computer and use it in GitHub Desktop.
Save and Restore DOM text selection
This file contains 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment