6

I've had a look round the web for solutions, and there are some, but they all seem to split code into supporting IE and Firefox.

I was wondering if there's a more elegant way which would work on every browser, to insert some text at the cursor in a textarea.

Thanks very much.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
richw81
  • 61
  • 1
  • 1
  • 2

2 Answers2

21

No, there isn't. IE has its TextRange objects to do the job. IE >= 9 and everything else for the last long time has selectionStart and selectionEnd properties on textareas and text inputs. This particular task isn't too bad: the following will delete the current selection (if one exists), insert text at the caret and reposition the caret immediately after the inserted text, in all the major browsers:

function insertTextAtCursor(el, text) {
    var val = el.value, endIndex, range;
    if (typeof el.selectionStart != "undefined" && typeof el.selectionEnd != "undefined") {
        endIndex = el.selectionEnd;
        el.value = val.slice(0, el.selectionStart) + text + val.slice(endIndex);
        el.selectionStart = el.selectionEnd = endIndex + text.length;
    } else if (typeof document.selection != "undefined" && typeof document.selection.createRange != "undefined") {
        el.focus();
        range = document.selection.createRange();
        range.collapse(false);
        range.text = text;
        range.select();
    }
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Thanks very much, thought that browsers might've moved on in the last few years but obviously IE's still choosing to be different. – richw81 Jul 22 '10 at 12:18
  • 1
    The good news is that IE 9 has `selectionStart` and `selectionEnd`. – Tim Down Jul 22 '10 at 13:35
  • This worked great for my implementation in all three browsers, the only problem I had was replacing selected text. If I replaced val.slice(0, endIndex) with val.slice(0, startIndex) it gave the functionality of highlighting a selection and replacing it with the added text. Just for others who needed the same functionality I did. – SomeoneRandom Sep 09 '13 at 14:50
  • it doesn't work as expected if you move the cursor using arrows – inside Feb 21 '18 at 20:26
0

implement both: the code that is supporting FF and the Code supporing the IE. You can use Frameworks to write Code for both browsers. Than the Framework will do the work of splitting the differences between the browsers.

It's sad, but browsers aren't 100% compatible!

jigfox
  • 18,057
  • 3
  • 60
  • 73