Tahazzot
Tahazzot

Reputation: 1262

Why after a click events keypress is happen two times?

I have click events when I click on the button and a keypress event's when I press enter key. But the problem is after a click on the button if I don't click on document and press enter key the process() function executes two times. I also try to fix it using the capture type but didn't find the solution.

It it happening for button focus?

How can I fix this double execution problem?

let

  button = document.querySelector('button'),
  input = document.querySelector('input');


button.addEventListener('click', process);
document.addEventListener('keypress', function(e){
  if (e.keyCode == 13)
     process();
});


function process(){
  console.log(
     input.value
  );
}
<input type="text" value="sometext"/>
<button> Action </button>

Upvotes: 2

Views: 1469

Answers (2)

The Chosen User
The Chosen User

Reputation: 23

Just remove the button focus. That's why it works two times.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074168

But the problem is after a click on the button if I don't click on document and press enter key the process() function executes two times.

That's because the button has focus, and when you press Enter (or Space) on a focused button, it triggers a click. You can prevent that by calling preventDefault in the keypress handler.

if (e.keyCode === 13 || e.keyCode === 32) {
   e.preventDefault();
}

Live Example:

let

  button = document.querySelector('button'),
  input = document.querySelector('input');


button.addEventListener('click', process);
document.addEventListener('keypress', function(e){
  if (e.keyCode === 13 || e.keyCode === 32) { // ***
     e.preventDefault();                      // ***
  }                                           // ***
  if (e.keyCode === 13) {
     process();
  }
});


function process(){
  console.log(
     input.value
  );
}
<input type="text" value="sometext"/>
<button> Action </button>

But keyCode is deprecated (so is keypress, the current recommendation is beforeinput or keydown), you might want to use key instead:

if (e.key === "Enter" || e.keyCode === " ") {
   e.preventDefault();
}

Live Example:

let

  button = document.querySelector('button'),
  input = document.querySelector('input');


button.addEventListener('click', process);
document.addEventListener('keypress', function(e){
  if (e.key === "Enter" || e.keyCode === " ") {
     e.preventDefault();
  }
  if (e.key === "Enter") {
     process();
  }
});


function process(){
  console.log(
     input.value
  );
}
<input type="text" value="sometext"/>
<button> Action </button>

Upvotes: 5

Related Questions