Working with the Selected Text in a TextArea Using JavaScript

Friday, July 31st 9:18pm Matt

Fueling my hatred of Internet Exporer, today I had to process this code. This function is based on Alex King’s work which has been adopted by WordPress. I adjusted his function to allow me to easily place tags around the selected text in a textarea.

I find it so horribly annoying that this bit of code is not standardized. As I search I’m not even quite sure who would standardize it. I don’t know if the API is part of the ECMAScript standard. But it needs to be a part of some standard and then tested in the ACID4 test.

Anyway, this is the code you’re looking for if you want to wrap an html tag around some selected text in a textarea. I use it in a WordPress plugin that creates a box on the edit post admin screen to allow that plugin to wrap bits of text with html code. I use Safari for development and the code works just fine in that browser.

function selectionSurround(element_id, before, after)
{
    var element = document.getElementById(element_id);
    
    if (document.selection) 
    {
        //IE support
        
        element.focus();
        sel = document.selection.createRange();
        sel.text = before + sel.text + after;
    }
    else if (element.selectionStart || element.selectionStart == '0') 
    {
        //MOZILLA/NETSCAPE support
        
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        element.value = 
              element.value.substring(0, startPos)
            + before
            + element.value.substring(startPos, endPos)
            + after
            + element.value.substring(endPos, element.value.length);
    } 
    else
    {
        element.value += myValue;
    }
}

Submit a Comment