I am having a scenario where I need to put cursor on text area and then click on tree view node on the same page to have selected node's text into my textarea where I placed cursor just before clicking on tree node.
I got many answers on Stack overflow including below,
Inserting text in textarea at cursor position if cursor placed else text should append at last in IE
Inserting text after cursor position in text areа
Insert text into textarea with jQuery
How to insert text at the current caret position in a textarea
Inserting text at cursor in a textarea, with Javascript
How do I insert some text where the cursor is?
FF and Chrome works fine with above solutions but IE 8 or lower version fails (didn’t check with IE9) if focus is moved to some other control.
There is below or similar implementation for IE in almost all posts:
(function ($) {
$.fn.getCursorPosition = function () {
var el = $(this).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength
}
return pos;
}
})(jQuery);
Note : We also can use if(el.selectionStart || el.selectionStart == '0')
instead of if ('selectionStart' in el)
and if(document.selection)
instead of if ('selection' in document)
But this will fail when focus is moved to some other control first and then executing it. In my case focus will be moved to tree nodes when user will traverse through nodes.
Is there any solution for this scenario?
I am thinking to write onkeyup and onclick on text area and save its cursor position into hidden field so when focus is moved to some other control, i will have hidden field to get cursor position of text area. I will post that here later, meanwhile if anyone has some good idea then please share.
Thank you in advance