Skip to content
Advertisement

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

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.

Advertisement

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.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement