0

I want to set the cursor to the beginning of the textbox(<input/>) always. I found following code below which does the job. However if there is a text in the textbox (<input/>)already, cursor is set at the end of the text first, then moved to the beginning. Which causes the jumping effect which is undesirable.

Is there a way to always set cursor to the begging without this jumping effect? Note I have function below called in onFocus onClick.

var range;
if (elem.createTextRange) {
    range = elem.createTextRange();
    range.move("character", 0);
    range.select();
} else if (elem.selectionStart) {

    elem.focus();
    elem.setSelectionRange(0, 0);
}
user_1357
  • 7,766
  • 13
  • 63
  • 106

1 Answers1

0

An alternative instead of doing it all by yourself is following jQuery plugin:

http://code.google.com/p/rangyinputs

A nice Demo can be found here: http://rangyinputs.googlecode.com/svn/trunk/demos/textinputs_jquery.html

Hope this brings some new light into your task, please understand that without a plunker / jsfiddle a perfect solution is out of my scope right now.

Update Another way would be to use (if you are in html5 context) the attribute autofocus. But the behavior is, that it gets the focus when the DOM was rendered and all existing text is selected. Don't know if you can live with this.

<input type="text" value="some text here" autofocus />

Update2

http://plnkr.co/Wag8fb @OP: please fork & edit it, so it works like your code. Because I used all your code pasted here and its not working at all.

angabriel
  • 4,979
  • 2
  • 35
  • 37