Norman
Norman

Reputation: 6365

jQuery: avoid checking if the key pressed is 'enter' everytime

In the code below, instead of using on keydown, is there a way I can use on e.which === 13 where the keydown is? This was it wont have to check each time a key is pressed, and will work only when enter is pressed.

Current Code

$('.search').on('keydown', function(e) {
    if(e.which === 13) {
        // enter key pressed
        var value = this.value; // this is the inputs value
        console.log(value);
    }
});

What I hope to do (pseudo code)

$('.search').(when key === 13 is pressed) { // Only if the enter key pressed

        // enter key pressed
        var value = this.value; // this is the inputs value
        console.log(value);
    }
});

Can something like this be done?

Upvotes: 0

Views: 119

Answers (3)

Renato Zannon
Renato Zannon

Reputation: 29941

You could use a higher-order function to extract that logic for you:

function onlyOnEnter(fn) {
  return function(e) {
    if(e.which === 13) {
      fn.apply(this, arguments);
    }
  }
}

Usage:

$('.search').on('keydown', onlyOnEnter(function(e) {
    var value = this.value; // this is the inputs value
    console.log(value);
  })
);

That way, your callback function will only be called when the key pressed is an enter.

Upvotes: 1

Ennui
Ennui

Reputation: 10190

No, this isn't really possible (at least not for the purposes of your code) nor does it make a lot of sense. The keydown event is fired whenever a key is pressed.

Whether you are manually checking to see if it's the enter key or whether the browser or jQuery is doing it internally isn't tremendously relevant - regardless the browser will need to check which key was pressed any time any key is pressed to test whether it was the enter key.

Essentially you're wasting your time. There isn't going to be any measurable performance optimization by trying to do this. No matter how you try to detect the enter key being pressed, it will be tested for every keydown or keypress event regardless of which key is pressed.

Upvotes: 1

Adriano Carneiro
Adriano Carneiro

Reputation: 58615

Not really.

The best you can do is capturing events (you are using on but it could be any other event capturing method). There are many different kind of events (mouse events, keyboard events, control specific events, etc.), you have to look at the event, since each event type will have different properties.

For key pressing, there are some events available for capturing such as keypress, keydown and keyup. You can't expect that one specific key will have an event on its own because you want so save one line of code.

Upvotes: 1

Related Questions