2

I'm trying to bring the typing cursor to beginning of the input text by this code with no success. What is the issue?

HTML
<input value="text"/>
JavaScript(jQuery)
$('input').focus(function(){
  $(this).delay(100).trigger(jQuery.Event("keydown",{keyCode: 36, which: 36}));
});

Live at JSBin

Mohsen
  • 64,437
  • 34
  • 159
  • 186

2 Answers2

3

This looks like a case of over thinking a problem OR you did not describe it properly. The default behavior of focus is to place the cursor at the beginning of text. Just do this:

$(function() {
    $('input').delay(100).trigger('focus');
});

Not sure why you need the delay. Using the jQuery ready event as shown you can elimintate the delay.

King Friday
  • 25,132
  • 12
  • 90
  • 84
  • if the text is empty, it comes to the beginning of the text because there is no other position, if the textbox has text, the default focus behaviour is to select all text. If you press home while all text is selected, it returns the cursor to a place before the first character. – Meligy Jan 14 '12 at 02:53
1

So, the problem is not really pressing home but moving cursor to beginning of the texbox I assune.

Checking this answer: move cursor to the beginning of the input field?
Generally the approach is right, but it doesn't seem to work directly

I have modified it to fit your jQuery on focus case:

$('input').focus(function(){
    var input = this;
    // for some reason, putting directly doesn't work
    setTimeout(function() { 
        if (input.createTextRange) {
                var part = input.createTextRange();
                part.moveat("character", 0);
                part.moveEnd("character", 0);
                part.select();
            }
        else if (input.setSelectionRange){
                input.setSelectionRange(0,0);
        }
    }, 0);
});

Live example:
http://jsfiddle.net/sF334/

If you want to trigger the focus itself, then you can do it as:

$('input').trigger('focus');
// use some unique selector instead in real example, like ID

Note it returns to before the first character on focus, but allows you to move and change selection later as you wish, as soon as you change focus and come back, it'll return to initial position again.

Community
  • 1
  • 1
Meligy
  • 35,654
  • 11
  • 85
  • 109