Textarea copy injector

I needed to build a UI component that injected some copy into a textarea. It needed to save any text that was already entered, and it needed to place the cursor at the end of the newly injected text (actually, it needed to select the last three characters). This is what I came up with:

$('#textareaInjectContent').bind('click', function (event) {
    var $eventTarget = $(event.target);

    if ($eventTarget.hasClass('text-inject')) {
        var $textarea = $("#textInjectee"),
            txtMessage = $textarea.val(),
            theCopy = $eventTarget.next().html(),
            newMessage = "";

        // trim spaces
        var txtMessage = txtMessage.replace(/^\s+|\s+$/g, '');

        // replace any non-breaking spaces
        var theCopy = theCopy.replace(' ', ' ');

        if (txtMessage === "") {
            newMessage = theCopy;
        }
        else {
            newMessage = theCopy + "\r\n\r\n" + txtMessage;
        }

        $textarea.val(newMessage);

        var textareaID = $textarea.attr('id');

        //Set position of cursor
        var textareaEl = document.getElementById(textareaID);
        if (textareaEl.setSelectionRange) {
            textareaEl.setSelectionRange((theCopy.length - 3), theCopy.length);
            //textareaEl.setSelectionRange(theCopy.length, theCopy.length);
        }
        else {
            e = textareaEl.createTextRange();
            e.collapse(true);
            e.moveEnd('character', theCopy.length);
            e.moveStart('character', theCopy.length - 3);
            e.select();
        }
        //Set focus on textarea
        document.getElementById(textareaID).focus();
        //$('#textCont').dialog('close');
    }
});

Here is the html structure:

<textarea id="textInjectee"></textarea>

<div id="textareaInjectContent">
<ul>
    <li>
        <button type="button" class="text-inject">Insert</button>
        <span class="text-to-inject">Turpis nonummy malesuada diam...</span>
    </li>
    <li>
        <button type="button" class="text-inject">Insert</button>
        <span class="text-to-inject">Lorem in suspendisse imperdiet fusce tortor purus et massa sit cras dignissim suscipit nec leo velit sapien et odio wisi lobortis ultrices lorem adipiscing...</span>
    </li>
    <li>
        <button type="button" class="text-inject">Insert</button>
        <span class="text-to-inject">Lobortis odio vel quisque ultricies in elit auctor...</span>
    </li>
</ul>
</div>

Here is a working jsfiddle: http://jsfiddle.net/McWatt/r99sC/embedded/result/

Leave a Reply