Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get last character before caret position in javascript

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);???
like image 842
Anoop Avatar asked Mar 01 '13 12:03

Anoop


1 Answers

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>
like image 149
Tim Down Avatar answered Nov 11 '22 22:11

Tim Down