get last character before caret position in javascript

Anoop picture Anoop · Mar 1, 2013 · Viewed 9.6k times · Source

I am about to implement Facebook like in integration in my contenteditable div where if i give '$' and some character like 'a' i need a auto-suggestion which should pop up near my caret position.

I need to know how to find out the last character before caret position either in JavaScript for IE and Other browsers. I have access to the Jquery library.

(function($) {
    $.fn.getCursorPosition = function() {
        var input = this.get(0);
        if (!input) return; // No (input) element found
        if ('selectionStart' in input) {
            // Standard-compliant browsers
            return input.selectionStart;
        } else if (document.selection) {
            // IE
            input.focus();
            var sel = document.selection.createRange();
            var selLen = document.selection.createRange().text.length;
            sel.moveStart('character', -input.value.length);
            return sel.text.length - selLen;
        }
    }
})(jQuery);

eg.
var caretPosition = $("#contenteditablediv").getCursorPosition();
var lastchar = getchar(caretposition -1);???

Answer

Tim Down picture Tim Down · Mar 1, 2013

Here's an example of how to do this. It creates a range that starts at the start of the editable element and ends immediately before the caret, gets the range's text and returns the last character of that range.

Demo: http://jsfiddle.net/MH5xX/

function getCharacterPrecedingCaret(containerEl) {
    var precedingChar = "", sel, range, precedingRange;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0).cloneRange();
            range.collapse(true);
            range.setStart(containerEl, 0);
            precedingChar = range.toString().slice(-1);
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        range = sel.createRange();
        precedingRange = range.duplicate();
        precedingRange.moveToElementText(containerEl);
        precedingRange.setEndPoint("EndToStart", range);
        precedingChar = precedingRange.text.slice(-1);
    }
    return precedingChar;
}

var editableEl = document.getElementById("editable");
var precedingCharEl = document.getElementById("precedingChar");

function reportCharacterPrecedingCaret() {
    precedingCharEl.innerHTML = "Character preceding caret: " + getCharacterPrecedingCaret(editableEl);
}

editableEl.onmouseup = editableEl.onkeyup = reportCharacterPrecedingCaret;
<div contenteditable="true" id="editable">Here is some text. Please put the caret somewhere in here.</div>
<div id="precedingChar" style="font-weight: bold"></div>