Skip to content Skip to sidebar Skip to footer

Get The Word Upon Which The Caret Sits Within A Contenteditable Div?

I am trying to extract a single word from a content editable div at the position, when the mouse is clicked. For example: Lorem ipsum dolor sit amet, cons|ectetur adipiscing elit.

Solution 1:

You could use the new TextRange module of my Rangy library for this, although it's enormous overkill just for that one feature. Here's the code you'd need:

var sel = rangy.getSelection();
sel.expand("word");
var word = sel.text();
alert(word);

Otherwise, if you can live with no support for pre-Blink Opera (up to and including version 12) and Firefox < 4, you could use Selection.modify() (WebKit, Firefox) and the expand() method of TextRange (IE). Here's an example.

Demo: http://jsfiddle.net/timdown/dBgHn/1/

Code:

function getWord() {
    var sel, word = "";
    if (window.getSelection && (sel = window.getSelection()).modify) {
        var selectedRange = sel.getRangeAt(0);
        sel.collapseToStart();
        sel.modify("move", "backward", "word");
        sel.modify("extend", "forward", "word");
        
        word = sel.toString();
        
        // Restore selection
        sel.removeAllRanges();
        sel.addRange(selectedRange);
    } else if ( (sel = document.selection) && sel.type != "Control") {
        var range = sel.createRange();
        range.collapse(true);
        range.expand("word");
        word = range.text;
    }
    alert(word);
}

Solution 2:

BitBucket have released their Cursores.js library that does this, it's small and focused which is nice - http://cursores.bitbucket.org/

The only issue I have is that it doesn't pick up the token if there is no text to the left of the caret, for example "t|est" would work but "|test" wouldn't.


Post a Comment for "Get The Word Upon Which The Caret Sits Within A Contenteditable Div?"