3

I have a textbox in my html body: input type="text" id="text-input"

I am using this to bring it into focus when the user presses enter:

<script>
    $(document).keypress(function(e) {
        if(e.keyCode == 13) {
            $("#text-input").focus();
        }
    });
</script>

The webpage I am using to try it out has only the text box in it. When I click on a blank area, and press enter, the "|" prompt will be misaligned downwards. If I repeat this clicking and pressing enter, the "|", which is supposed to be in the textbox, keeps moving down more and more.

What went wrong?

Legendre
  • 3,108
  • 7
  • 31
  • 46
  • 2
    I assume you're referring to the cursor? What browser? Perhaps a jsfiddle example? – chrismarx Apr 27 '12 at 17:26
  • Jsfiddle of a test case and browser information will be really helpful. – MetalFrog Apr 27 '12 at 17:27
  • I'll help: http://jsfiddle.net/RUb2P/ I'm using Chrome 18. To reproduce, place the mouse cursor below (outside) the text box. Click, then press enter. Repeat these two steps over and over. Also, Some odd behavior happens when text is entered, but I don't have specific directions to make them happen. – Heitor Chang Apr 27 '12 at 17:31
  • Oh yes the cursor. Browser: Google Chrome, up to date. http://jsfiddle.net/n8PDc/ 1) Click in the textbox. The cursor is fine. 2) Click on white space nearby to defocus textbox. 3) Press enter to focus. Cursor should be off. – Legendre Apr 27 '12 at 17:31

2 Answers2

1

Try using keyup instead of keypress

$(document).keyup(function(e) {
    if(e.keyCode == 13) {
        $("#text-input").focus();
    }
});​

Example: keypress and keyup

Tested in chrome and results are different.

Note: keypress=(keydown and keyup 2 events). May be this is the issue but not sure.

The Alpha
  • 143,660
  • 29
  • 287
  • 307
1

I found that returning false corrects the behavior:

$(document).keypress(function(e) 
{
    if(e.keyCode === 13) 
    {
        $("#text-input").focus();

        return false;
    }
});​

To improve on this, you could actually use the combination of e.preventDefault(); and e.stopImmediatePropagation(); instead of return false; to ensure that once this handler is hit, nothing else happens but the .focus() that you are intending:

$(document).keypress(function(e) 
{
    if (e.keyCode === 13) 
    {
        $("#text-input").focus();

        e.preventDefault();
        e.stopImmediatePropagation();
    }
});

The only caveat is that e.stopImmediatePropagation(); only works for event handlers defined after this handler in your code. Meaning, if you had another handler bound to the document's keypress prior to your .focus(), it would continue to be hit. Therefore, to make sure this and only this is called, you would need make sure it was the first handler defined in your code.

See an example here

Code Maverick
  • 20,171
  • 12
  • 62
  • 114