Get/set Cursor In Html TextArea


/ Published in: JavaScript
Save to your folder(s)

I got this code from http://blog.vishalon.net/Post/57.aspx


The actual two methods required are

function doGetCaretPosition (ctrl) {
var CaretPos = 0;
// IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}

function setCaretPosition(ctrl, pos)
{
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}


Copy this code and paste it in your HTML
  1. <html>
  2. <head>
  3. <title>Get/Set Caret in Textarea Example</title>
  4. <script>
  5. function doGetCaretPosition (ctrl) {
  6.  
  7. var CaretPos = 0;
  8. // IE Support
  9. if (document.selection) {
  10.  
  11. ctrl.focus ();
  12. var Sel = document.selection.createRange ();
  13.  
  14. Sel.moveStart ('character', -ctrl.value.length);
  15.  
  16. CaretPos = Sel.text.length;
  17. }
  18. // Firefox support
  19. else if (ctrl.selectionStart || ctrl.selectionStart == '0')
  20. CaretPos = ctrl.selectionStart;
  21.  
  22. return (CaretPos);
  23.  
  24. }
  25.  
  26.  
  27. function setCaretPosition(ctrl, pos)
  28. {
  29.  
  30. if(ctrl.setSelectionRange)
  31. {
  32. ctrl.focus();
  33. ctrl.setSelectionRange(pos,pos);
  34. }
  35. else if (ctrl.createTextRange) {
  36. var range = ctrl.createTextRange();
  37. range.collapse(true);
  38. range.moveEnd('character', pos);
  39. range.moveStart('character', pos);
  40. range.select();
  41. }
  42. }
  43.  
  44. function process()
  45. {
  46. var no = document.getElementById('no').value;
  47. setCaretPosition(document.getElementById('get'),no);
  48. }
  49.  
  50. </script>
  51. </head>
  52. <body>
  53. <textarea id="get" name="get" rows="5" cols="31">Please write some integer in the textbox given below and press "Set Position" button. Press "Get Position" button to get the position of cursor.</textarea>
  54. <br>
  55.  
  56. Enter Caret Position: <input type="text" id="no" size="1" /><input type="button" onclick="process();" value="Set Position">
  57. <BR>
  58. <input type="button" onclick="alert(doGetCaretPosition(document.getElementById('get')));"
  59. value="Get Position">
  60. </body>
  61. </html>

URL: http://demo.vishalon.net/getset.htm

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.