$(document).keydown event handler not getting triggered the first time

$(document).keydown event handler not getting triggered the first time

So I have an event handler for the KeyDown event in a Javascript file but for some reason it does not get called the first time a key is pressed. However, if a key is pressed or a mouse button clicked then the next time I press a key it does get called. Here is the relevant code:

  1. ...........................
  2. // Other stuff
  3. $(function()
  4. {
  5.       //Other stuff
  6.       .............................
  7.       $(document).keydown(function(e)
  8.     {
  9.         alert('keydown event');
  10.       .................................
  11.       // Other stuff

The outcome of the code above is that the first time a key is pressed nothing happens. The second time it is pressed the Alert gets displayed normally. Why is this happening?