contenteditable selected text save and restore

Hussein picture Hussein · Jan 14, 2011 · Viewed 15.5k times · Source

I came across this post that shows 2 functions on how to save and restore selected text from a contenteditable div. I have the below div set as contenteditable and the 2 function from the other post. How to i use these functions to save and restore selected text.

<div style="width:300px;padding:10px;" contenteditable="true">test test test test</div>

<script>
function saveSelection() {
    if (window.getSelection) {
        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) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}
</script>

Answer

Tim Down picture Tim Down · Jan 14, 2011

A typical use would be displaying some kind of widget or dialog to accept input from the user (thus potentially destroying the original selection) and restoring the selection after that widget has been hidden. Actually using the functions is quite simple; the biggest danger is trying to save the selection after it has already been destroyed.

Here's a simple example. It displays a text input and overwrites the selection in the editable <div> with the text from that input. There's too much code to paste in here, so here's the full code: http://www.jsfiddle.net/timdown/cCAWC/3/

Extract:

<div id="test" contenteditable="true">Some editable text</div>
<input type="button" unselectable="on" onclick="displayTextInserter();"
    value="Insert text">
<div id="textInserter">
    <input type="text" id="textToInsert">
    <input type="button" onclick="insertText()" value="Insert">
</div>

<script type="text/javascript">
var selRange;

function displayTextInserter() {
    selRange = saveSelection();
    document.getElementById("textInserter").style.display = "block";
    document.getElementById("textToInsert").focus();
}     

function insertText() {
    var text = document.getElementById("textToInsert").value;
    document.getElementById("textInserter").style.display = "none";
    restoreSelection(selRange);
    document.getElementById("test").focus();
    insertTextAtCursor(text);
}
</script>