Tuesday, June 25, 2013

Preserve text selection in contenteditable while interacting with jQuery

You could save and restore the selection using simple functions such as the following when the dialog is opened and closed. I am not familiar enough with jQuery dialogs to know the mechanism for hooking into the dialog opening and closing. The first, saveSelection, returns you a Range or TextRangeobject that you should store in a variable which you later pass to restoreSelection:
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();
        }
    }
}

No comments:

Post a Comment