Thursday, 22 November 2018

Modify selection, select word and then reattach the caret position

So i'm trying to make a wysiwyg editor in javascript. What i'm trying to do is: when I havent made a selection and only stand with the caret on a word, I want to select the word, execute a command on it and then move the caret back to its position.

Example: Before I execute my code (the caret should be here after my function):

make this word b|old

After:

make this word bold|

jsFiddle Example: jsFiddle

My code so far:

    if (window.getSelection && (sel = window.getSelection()).modify) {
        doc.focus(); // the editor
        var range = sel.getRangeAt(0);
        var oldRange = document.createRange();
        oldRange.setStart(range.startContainer, range.startOffset);
        oldRange.setEnd(range.endContainer, range.endOffset);

        sel.collapseToStart();           

        sel.modify("move", "forward", "character");
        sel.modify("move", "backward", "word");
        sel.modify("extend", "forward", "word");

        document.execCommand(command, false, value);

        // Restore selection, Dosen't work as I expected
        sel.removeAllRanges();
        sel.addRange(oldRange);
}



from Modify selection, select word and then reattach the caret position

No comments:

Post a Comment