75

Is there an addEventListener for the Enter key?

I have

document.querySelector('#txtSearch').addEventListener('click', search_merchants);

I know this is intended for <button>, but wanted to know if there's an equivalent for catching the Enter key.

Jeremy
  • 767
  • 1
  • 5
  • 7

3 Answers3

145

Are you trying to submit a form?

Listen to the submit event instead.

This will handle click and enter.

If you must use enter key...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});
Trevor
  • 11,269
  • 2
  • 33
  • 40
  • 5
    As a tip , ````document.addEventListener('keypress', function (e) {}```` . Using directly without ````querySelector```` in case you need more response from any enter strike like login form . – mercury Sep 26 '17 at 04:49
  • 6
    One important detail *e.which* and *e.keyCode* are currently deprecated the new correct way is *e.key* **References** //e.which https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which //e.keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode //e.key https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key – Juanma Menendez Mar 25 '19 at 03:41
  • The `keypress` event has also been deprecated ([link to MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event)) please use the `keydown` event: [link to MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event) – magikMaker Aug 16 '23 at 08:12
24

Here is a version of the currently accepted answer (from @Trevor) with key instead of keyCode:

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});
Marcus
  • 3,459
  • 1
  • 26
  • 25
11

You could listen to the 'keydown' event and then check for an enter key.

Your handler would be like:

function (e) {
  if (13 == e.keyCode) {
     ... do whatever ...
  }
}
JasonFruit
  • 7,764
  • 5
  • 46
  • 61
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73