Please visit my new Web Site https://coderstechzone.com
Basically when we want to create an editor like interface then set or get cursor postion is one of the most important task. Here i want to share two cross-browser supported javascript methods which will meet your requirements To Set cursor position into a TextArea & To Get cursor position from TextArea:
Get cursor postion using javascript method:
function GetCursorPosition()
{
// HERE txt is the text field name
var obj=document.getElementById('<%= txt.ClientID %><%= txt.ClientID %>');
var CurPos = 0;
//FOR IE
if (document.selection)
{
obj.focus ();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -obj.value.length);
CurPos = Sel.text.length;
}
// For Firefox
else if (obj.selectionStart obj.selectionStart == '0')
CurPos = obj.selectionStart;
return CurPos;
}
{
// HERE txt is the text field name
var obj=document.getElementById('<%= txt.ClientID %><%= txt.ClientID %>');
var CurPos = 0;
//FOR IE
if (document.selection)
{
obj.focus ();
var Sel = document.selection.createRange();
Sel.moveStart ('character', -obj.value.length);
CurPos = Sel.text.length;
}
// For Firefox
else if (obj.selectionStart obj.selectionStart == '0')
CurPos = obj.selectionStart;
return CurPos;
}
Set cursor postion using javascript method:
function SetCursorPosition(pos)
{
// HERE txt is the text field name
var obj=document.getElementById('<%= txt.ClientID %><%= txt.ClientID %>');
//FOR IE
if(obj.setSelectionRange)
{
obj.focus();
obj.setSelectionRange(pos,pos);
}
// For Firefox
else if (obj.createTextRange)
{
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
{
// HERE txt is the text field name
var obj=document.getElementById('<%= txt.ClientID %><%= txt.ClientID %>');
//FOR IE
if(obj.setSelectionRange)
{
obj.focus();
obj.setSelectionRange(pos,pos);
}
// For Firefox
else if (obj.createTextRange)
{
var range = obj.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
Script tested for below Browsers:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome
1 comments:
How can i use the set cursor position script in my page?
And it is possible to control the mouse button with javascript?
I WOULD BE DELIGHTED TO HEAR FROM YOU