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?
If there is no selection, you can use the properties . selectionStart or . selectionEnd (with no selection they're equal). var cursorPosition = $('#myTextarea').
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).
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With