[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1666
  • Last Modified:

Inserting text at the cursor position within a textarea using javascript

Good morning.  I need to figure out how to reliably Insert text at the EXACT cursor position within a textarea using javascript.  

In doing some quick research on the topic, I learned that this works inconsistently across different browsers, and my tests have confirmed this as well.

For example, .. it seems to work pretty well in Internet Explorer, .. but Firefox seems to have a problem with it.  And I haven't even tested it in Safari.  

Does anyone here know of a way that I could custom program this type of functionality (perhaps using javascript-based user agent detection which writes in different javascript based on which browser is detected) -- so that it works consistently across browsers? Ideally, I'd like to get it to work consistently in Internet Explorer, Firefox, and Safari.    

Or ... is inserting text at the EXACT cursor position within a textarea only possible In Internet Explorer?  Please advise.

- Yvan

1 Solution
Michel PlungjanIT ExpertCommented:
I have only seen IE do this consistently
Firefox might have a way too....

The search is the title of your question plus firefox


and another word to use is Caret which is the cursor in the textarea
I use this JS-function to do this:
* This function inserts a text at the current cursor position
* @param string text to insert at current position
* @param DOMElement field in which the value should be inserted
function insertAtCurrentPosition(value, dest)
    /* for Internet Explorer */
    if (document.selection) {
        var sel = document.selection.createRange();
        sel.text = value;
    /* for Mozilla */
    else if (dest.selectionStart || dest.selectionStart == '0') {
        var startPos = dest.selectionStart;
        var endPos = dest.selectionEnd;
        dest.value = dest.value.substring(0, startPos)
            + value
            + dest.value.substring(endPos, dest.value.length);
    } else {
        dest.value += value;

IDEASDesignAuthor Commented:
Thanks so much! The script works great!

- Yvan

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now