2

If a user is typing in an input field, I know that you can focus on the element to put the cursor there, but is there a way to position the cursor in the input? say half way? thanks

TheExit
  • 5,220
  • 12
  • 37
  • 49

1 Answers1

1

Try this

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

associate this function to the onkeyup, onkeydown and onmouseup and onmousedown to get the location tryit out over here

Amit Gupta
  • 577
  • 4
  • 14
  • maybe its too late its firefox issue on jsfiddle. try console.log in fiddle istead of innerText. This function works fine. – Amit Gupta Apr 03 '13 at 12:12