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

Go To StackoverFlow.com

1

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.

2012-04-05 23:26
by HappyDeveloper
I'm pretty sure something else is making it slow. Because that code shouldn't make it noticeably slower - PeeHaa 2012-04-05 23:32


3

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
});
2012-04-05 23:37
by Starx
Very creative, lemme try it out. Br - HappyDeveloper 2012-04-05 23:42


0

I would try this:

document.onkeydown = function(event) {
  if(event.keyCode == '13') {
    // do something
    return false;
  }
};

This puts the event listener at the top of the DOM graph, giving it the first chance to respond. Returning false also tells the browser that the event is handled. This will prevent it from 'asking' other elements about the event. Also ditching jQuery and managing the event directly will avoid executing more JS than it needs to.

If this is stil slow, I would have to think theres logic elsewhere slowing it down. If this is a chat, adding/rearranging DOM elements in the chat body can cause significant browser overhead. You should try using setInterval to trigger the 'enter' logic every few seconds or so. Try typing (itll randomly send the message), but if you still experience the slowdown, it must be some other logic.

2012-04-05 23:55
by Colin Godsey
Ads