Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current cursor position in a textbox

I need a code to find current position of cursor in a textbox/textarea. It should work with chrome and firefox. Following is the code which I am using:

<!DOCTYPE html> <html>   <head>     <script>       function textbox()       {         document.getElementById('Javascript_example').value = document.activeElement.id;         var ctl = document.getElementById('Javascript_example');         alert(ctl);          var startPos = ctl.selectionStart;         alert(startPos);         var endPos = ctl.selectionEnd;         alert(endPos);       }     </script>   </head>   <body>      <input id="Javascript_example" name="one" type="text" value="Javascript_example" onclick="textbox()">    </body> </html> 

Any suggestion?

like image 504
Perseus Avatar asked Apr 19 '13 13:04

Perseus


People also ask

How do I find the cursor position in text area?

If there is no selection, you can use the properties . selectionStart or . selectionEnd (with no selection they're equal). var cursorPosition = $('#myTextarea').

How can get current cursor position in textbox using jQuery?

For exactly what you're after, there's the jQuery Caret (jCaret) plugin. For your code to get the position you could do something like this: $("#myTextInput"). bind("keydown keypress mousemove", function() { alert("Current position: " + $(this).

How do I get the input field cursor?

To move the cursor to the beginning of an input field:Use the setSelectionRange() method to move the cursor to the beginning of the input field. Call the focus() method on the input element. The focus method will move the cursor to the beginning of the element's value.

How do I get a caret position?

You also need the input's selectionDirection to get the caret position whenever selectionDirection is backward i.e. you make a selection left-ward in the textbox so that selectionStart is the caret, but when selectionDirection is forward the caret will be at selectionEnd.


1 Answers

It looks OK apart from the space in your ID attribute, which is not valid, and the fact that you're replacing the value of your input before checking the selection.

function textbox()  {          var ctl = document.getElementById('Javascript_example');          var startPos = ctl.selectionStart;          var endPos = ctl.selectionEnd;          alert(startPos + ", " + endPos);  }
<input id="Javascript_example" name="one" type="text" value="Javascript example" onclick="textbox()">

Also, if you're supporting IE <= 8 you need to be aware that those browsers do not support selectionStart and selectionEnd.

like image 81
Tim Down Avatar answered Sep 23 '22 01:09

Tim Down