Select the whole word before the cursor

by Budhram Gurung

HTML

<div id="status">Move the caret on the text:</div>
<textarea id='content'>Here's a bunch of words</textarea>
<div id="wordBeforeCursor"></div>

JavaScript

function getCaret(el) {
    return el.selectionStart;
}


window.onload = function () {
    var textarea = document.getElementById('content'),
        status = document.getElementById('status');

    textarea.onmouseup = textarea.onkeyup = function () {
        status.innerHTML = getCaret(textarea);

        var char = $('#content').val().split('');
        var before = char.slice(0, getCaret(textarea));
        words = before.join('').split(' ');
        var word = words.pop();
        last=words.length-1;
        wordBeforeCursor.innerHTML = words[last] ? words[last] :'';
    };
};