Jeremy Jeremy - 5 months ago 36
Javascript Question

EventListener Enter Key

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.

Answer

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) {
    var key = e.which || e.keyCode;
    if (key === 13) { // 13 is enter
      // code for enter
    }
});
Comments