views:

91

answers:

1

Is there anyway to check if the character at the cursor in TEXTAREA is a "space"? If it is, return TRUE. Let me know how to do this using jQuery.

Thanks

+2  A: 

This works in recent versions of the main browsers and has the added bonus of not requiring jQuery or any other library:

function nextCharIsSpace(textArea) {
    var selectedRange, range, selectionEndIndex;

    // Non-IE browsers
    if (typeof textArea.selectionEnd == "number") {
        selectionEndIndex = textArea.selectionEnd;
    }

    // IE is more complicated
    else if (document.selection && document.selection.createRange) {
        textArea.focus();
        selectedRange = document.selection.createRange();
        range = selectedRange.duplicate();
        range.moveToElementText(textArea);
        range.setEndPoint("EndToEnd", selectedRange);
        selectionEndIndex = range.text.length;
    }
    return textArea.value.charAt(selectionEndIndex) === " ";
}
Tim Down
Does this work for non-selected text in a text area?... I was looking for something like this for an old project
fudgey
How do you mean? It works both when the selection is empty (i.e. just a caret) or a selection.
Tim Down