April 5, 2012

How to bind enter key to callback in Javascript without slowing down the typing?

Question by HappyDeveloper

I need this for a chat box. When the user press enter, I want to trigger a callback (to send the message and clean the input field)

So far I got this, but the typing becomes slow:

$('#chat_input').keydown(function(event) {
  if(event.keyCode == '13') {
    // do something
  }
});

How would you optimize this?

UPDATE: It’s not a huge slow down, but I can feel it. I’m pretty sure this code is the responsible. I have always had this problem, so I thought it was about time to find a different way if possible.

Answer by Starx

No, your code are not the guilty one here. Since you are building a chat system, you must be running other scripts as well. But here is another way to look into the problem.

Make a mini form

<form name="chatline" ... >
   <input type="text" />
   <input type="submit" />
</form>

Then catch the submit event of the form, which will be triggered on enter automatically by the browser

$("form").submit(function() {
    //there you go, you caught your enter
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!