Cursor Position in Textbox Using JavaScript


This article is written by Pon Saravanan  on 02-Nov-09 Last modified on :04-Apr-10





Javascript Cursor Position in TextBox

In JavaScript getting the cursor position in textbox differs browsers to browsers. Firebox’s solution is simpler while internet explorer the solution is not straight forward and as well the result may not be accurate all the times. So the following is a simple approach to get the location of the cursor. It may not be accurate but simple and easy to understand.

Internet Explorer and the Range Object

To get the caret location we need to work with selection to get it. To get the selection we can use document. Selection(Cursor Position in Textbox Javascript can be used with range).. Then a range from the selection can be taken by the selection object's createRange. This gives the range. Once the range is available the rest is simple calculations only. This script can be moved to a Javascript file for using in different places.

Sample Events are

OnMouseDown
OnMouseUp
OnKeyUp
OnKeyDown

Javascript source code to find cursor position

MarkUp and JavaScript

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>
    <script type="text/javascript">
        function GetCursorLocation(CurrentTextBox)
        {
            var CurrentSelection, FullRange, SelectedRange, LocationIndex = -1;
            if (typeof CurrentTextBox.selectionStart == "number")
            {
                LocationIndex = CurrentTextBox.selectionStart;
            }
            else if (document.selection && CurrentTextBox.createTextRange)
            {
                CurrentSelection = document.selection;
                if (CurrentSelection)
                {
                    SelectedRange = CurrentSelection.createRange();
                    FullRange = CurrentTextBox.createTextRange();
                    FullRange.setEndPoint("EndToStart", SelectedRange);
                    LocationIndex = FullRange.text.length;
                }
            }
            return LocationIndex;
        }
        function DisplayCursorLocation(CurrentTextBox)
        {
            document.getElementById('Result').innerText = 'Location is ' + GetCursorLocation(CurrentTextBox);
        }
    </script>
</head>
<body>
    <form action="test.htm">
    <input type="text" id="txtInput" onmousedown="DisplayCursorLocation(this)" onmouseup="DisplayCursorLocation(this)"
        onkeyup="DisplayCursorLocation(this)" onkeydown="DisplayCursorLocation(this)" />
    <div id="Result">
    </div>
    </form>
</body>
</html>










Comments
  • GUEST
    thanks man 10/7/2011 3:06:05 AM


Comments
   
Captcha Image
For you specially:  
Captcha Text Enter the text in the image.(Not Case sensitive)    



Spam Bot Trap



   



Select Theme
White
Blue
Brown
Gray