0

So because I need to workaround some built-in form functionality in software that we use, I want to trigger a click on an element, by pressing enter.

This is my script:

let submitButton = document.querySelector('.test');

submitButton.addEventListener('click', submitForm, false);

submitButton.addEventListener('keydown', function(key) {
  if (key.keyCode == '13') {
    key.preventDefault();
    submitButton.click();
  }
});

function submitForm() {
  // do something
}

Clicking on the div with class="test" triggers an external script which only gets triggered on button click. Now for user experience I want to trigger this aswell on press of enter. According to documentation it should be like the above, but pressing enter doesn't trigger the script.

Does anybody know how to fix this?

  • Adding your `keydown` listener to the closest focussed parent element OR to `window` object itself should help you. – Silvan Bregy Nov 01 '21 at 14:56
  • If that's a form that contains input element, you may listen for changes in that particular field and trigger [form submit](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit) on Enter key pressed. – Yevhen Horbunkov Nov 01 '21 at 15:00
  • You need to make your div "focusable", this can be achieved by adding it a tabindex, as shown in https://stackoverflow.com/questions/148361/how-can-i-give-keyboard-focus-to-a-div-and-attach-keyboard-event-handlers-to-it – José Carlos PHP Nov 01 '21 at 15:04
  • Does this answer your question? [How can I give keyboard focus to a DIV and attach keyboard event handlers to it?](https://stackoverflow.com/questions/148361/how-can-i-give-keyboard-focus-to-a-div-and-attach-keyboard-event-handlers-to-it) – José Carlos PHP Nov 01 '21 at 15:05

0 Answers0