EventListener Enter Key

Javascript

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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
    }
});

Solution 2 - Javascript

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
    }
});

Solution 3 - Javascript

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 ...
  }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremyView Question on Stackoverflow
Solution 1 - JavascriptTrevorView Answer on Stackoverflow
Solution 2 - JavascriptMarcusView Answer on Stackoverflow
Solution 3 - JavascriptRichard SchneiderView Answer on Stackoverflow