get last character before caret position in javascript
Asked Answered
Q

1

15

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);???
Qnp answered 1/3, 2013 at 12:9 Comment(2)
That function won't work for contenteditable elements in non-IE browsers. it's for inputs and textareas.Grecize
yes i know it was just a example.. can you suggest me some other way to find the last character before caret position??Qnp
G
30

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>
Grecize answered 1/3, 2013 at 12:27 Comment(6)
hi its works like a charm. Thanks. I have got one more problem. I am using Infragistics content-Editor. So in IE it will be a div but in Chrome it will be a iframe. I tried with iframe and its not working.. can you tell me how will i find it in iframe.ThanksQnp
@Anoop: You'll need to replace the references to document and window with document and window objects obtained from the iframe. Shouldn't be too hard.Grecize
Thanks.It worked for me.For Chrome with Iframe i used document.getElementById('iframe_id').contentDocument.getSelection() instead of window.getSelection. And i used range.setStart(containerEl.contentDocument.body, 0); insead of range.setStart(containerEl, 0);Thanks once again. can u suggest me any solution for this link how to show an auto suggestion div near the caret position in a content-editable divQnp
Hopefully someone else could find this useful such as I did for finding the character immediately after the caret. Many thanks to @TimDown for his extra help jsfiddle.net/MH5xX/139Bealle
@Bealle it seem I found a solution for getting character after the caret: you just need to use range.setEndAfter(range.endContainer) instead of range.setStart(containerEl, 0) and then get first character of this range: range.toString()[0]Dylan
Looking for this for weeks ! Thank you Tim ;)Angeli

© 2022 - 2024 — McMap. All rights reserved.