How can I combine the callback of the click event with the callback of the keydown event?

Tags:



While I was coding, I have noticed that I am repeating the same code twice in two callback functions:

document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    UI.events.form.password.show();
  }
});
document.querySelector(DOM.next).addEventListener('click', (e)=>{
    e.preventDefault();
    UI.events.form.password.show();
});

I have tried to write some algorithm which allows me to implement this goal, but still I am unable to reach that goal.

Answer

Introduce a new function and move the common logic to that function.

Please have a look.

function showPassword(event) {
    event.preventDefault();
    UI.events.form.password.show();
}


document.querySelector(DOM.usernameInput).addEventListener("keydown", e => {
  if (e.keyCode === 13) {
   showPassword(e);
  }
});

document.querySelector(DOM.next).addEventListener('click', showPassword);

I Hope this helps you.



Source: stackoverflow