I had an interesting challenge today. I have a screen that has multiple text fields and multiple inputs that are actually images (default to submit). There was, by the way, not a single form on this page.

Internet Exploder Explorer was doing me the favor of ASSUMING I wanted the form submitted when a user pressed the enter key in a text field. So IE kicked off the onclick event of the FIRST submit/image on the page.

I decided to trap the enter key and use it for good rather than evil.

The YUI.util has a KeyListener that seemed to be what I was looking for. Yes, I could have just trapped the keypress event myself, but I LIKE to use YUI.

Turns out the documentation on this one is pretty good, but there are no straightforward examples. So, I'll just note here that you want to make sure you declare your KeyListener and then call the enable() method. Otherwise, it dosn't do anything for you.

myListener = YAHOO.util.KeyListener("watchNode", {keys:13}, functionToDo);

For some reason, this was not entirely apparent to me. Took me a while to figure it out. Hopefully, I just saved you some time.


  1. Can you show a working example?

  2. Thanks you're right no clear cut example, thanks for the post.

  3. Thanks! Love the "hope to save you some time" posts.

  4. I think the 'new' keyword is essential. Also, for me, it was important to pass the scope of the current object to the function handler. For this, scope is not enough, you need correctScope:

    this.enterPass =new YAHOO.util.KeyListener(
    { fn:this.btn_login_click,