Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ckeditor - get previous character of current cursor position

Tags:

ckeditor

How to get previous character of current cursor position in ckeditor? for example, assume '|' char is the cursor position in "Hello| World" text then I want to get 'o' character.

like image 570
Mosiur Avatar asked Jan 07 '14 13:01

Mosiur


1 Answers

Given that editor is one of CKEDITOR.instances, the following should do the trick:

function getPrevChar() {
    var range = editor.getSelection().getRanges()[ 0 ],
        startNode = range.startContainer;

    if ( startNode.type == CKEDITOR.NODE_TEXT && range.startOffset )
        // Range at the non-zero position of a text node.
        return startNode.getText()[ range.startOffset - 1 ];
    else {
        // Expand the range to the beginning of editable.
        range.collapse( true );
        range.setStartAt( editor.editable(), CKEDITOR.POSITION_AFTER_START );

        // Let's use the walker to find the closes (previous) text node.
        var walker = new CKEDITOR.dom.walker( range ),
            node;

        while ( ( node = walker.previous() ) ) {
            // If found, return the last character of the text node.
            if ( node.type == CKEDITOR.NODE_TEXT )
                return node.getText().slice( -1 );         
        }
    }

    // Selection starts at the 0 index of the text node and/or there's no previous text node in contents.
    return null;
}

Check the jsFiddle. Give it a try: put the caret anywhere but mostly before ^ to see if tricky cases are covered.

like image 153
oleq Avatar answered Oct 17 '22 04:10

oleq