Search code examples
jqueryevent-handlingonkeydownonkeypress

Is jQuery.one() possibly a bad idea for attaching multiple event handlers?


There is an <input type="text"> on a form and when I click it to give it focus and I start typing the first char I enter is ignored. The input starts filling from the second on.

There must be something in the page that is consuming the first char. How can I find what that is?

Even if I click the input several times before typing, the first char gets slurped.

The only peculiarities I am aware of in this situation are:

  • beforehand there was a <div class="overlay"> covering the whole page. The overlay went into display:none; with a click. I have tried deleting the div using the devTools, in case it was still intercepting stuff, but the problem remained
  • the tabindex properties of the form have been manipulated with jQuery instructions

I have verified the problem in Chrome37, IE11 and FF32.


Solution

  • OK, I found the bug. Let's put the solution here and change the question title, because it is interesting...

    Going through the code for the tenth time (someone else's code obviously...) I observe the peculiar way the event handler got attached:

    $(document).one("keydown mousedown touchstart", function(ev) {
      ev.preventDefault();
      self.hideOverlayDiv();
    })
    

    $.one is used, probably trying to avoid to have to remove explicitly the event handler after the run.

    Problem is: after I consume the mousedown event handler, there are two more event handlers ready to run on keydown and touchstart events. And when I begin filling the input, the onkeydown fella slurps my first char.

    I have changed the thing like this:

    $(document).on("keydown mousedown touchstart", function(ev) {
      ev.preventDefault();
      self.hidePopupError();
      $(document).off("keydown mousedown touchstart");
    })