Tuesday, March 3, 2009

Javascript: How to set/get cursor position of a textarea




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;
}

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();
}
}

Script tested for below Browsers:
1. Internet Explorer
2. Mozilla Firefox
3. Opera
4. Google Chrome

1 comments:

profilcaleg said...

How can i use the set cursor position script in my page?
And it is possible to control the mouse button with javascript?

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash