Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gitSambhal/d305b2b5442c5019f2b5caf2bf28a40d to your computer and use it in GitHub Desktop.
Save gitSambhal/d305b2b5442c5019f2b5caf2bf28a40d to your computer and use it in GitHub Desktop.

Revisions

  1. Israel Cruz revised this gist Dec 9, 2016. 1 changed file with 17 additions and 0 deletions.
    17 changes: 17 additions & 0 deletions save-and-restore-contenteditable-selection.js
    Original file line number Diff line number Diff line change
    @@ -22,4 +22,21 @@ function restoreSelection(range) {
    }
    }

    /**
    * 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
  2. Israel Cruz created this gist Dec 9, 2016.
    25 changes: 25 additions & 0 deletions save-and-restore-contenteditable-selection.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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();
    }
    }
    }

    // Credits: Tim Down's SO answer http://stackoverflow.com/a/3316483/1470564