0

The timeout of 0 is used here so that the keypress has time to end before blurring the control. This strikes me as the wring way to achieve this...

$(document).keypress(function(e){
  if( e.keyCode === 13){
    setTimeout(function(){
      $('input').blur();
    }, 0);
  }
});

What is a better way to blur controls when the enter key is pressed?

Billy Moon
  • 57,113
  • 24
  • 136
  • 237

3 Answers3

1

You don't need setTimeout here:

$(document).keypress(function(e){
  if( e.keyCode === 13){
      $('input').blur();
  }
});

The demo.

xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Why not try using keyup event, so that you have a small amount of time before the user releases the key.

$(document).keyup(function(e){
  if( e.keyCode === 13){
      $('input').blur();
  }
});

Check Fiddle

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
0

You might be surprised to learn that there is no such thing as a timeout of zero. The minimum timeout value of Chrome is 8ms and the minimum of Firefox is 15ms.

Joe Simmons
  • 1,828
  • 2
  • 12
  • 9
  • Although rare, there may be some cases where timeout of 0 does indeed exist: http://stackoverflow.com/a/7221609/665261 – Billy Moon Aug 07 '13 at 08:46