1

I don't understand why with Firefox when I launch keydown event with space my click event is also launched.

With enter no problem.

var eventFunction = function(e) {
  if (content.style.display === 'none' || content.style.display === '') {
    content.style.display = 'block';
  } else {
    content.style.display = 'none';
  }
}
button.addEventListener('click', function(e){
  console.log('click');
  eventFunction(e);
  this.removeEventListener('click', eventFunction, false);
}, false);
button.addEventListener('keydown', function(e) {
  console.log('keydown');
  if(e.keyCode === 13 || e.keyCode === 32) {
    eventFunction(e);
    e.stopPropagation();
    e.preventDefault();
    this.removeEventListener('keydown', eventFunction, false);
  }
}, false);

Demo here : https://jsfiddle.net/korigan/f371vcxx/

epascarello
  • 204,599
  • 20
  • 195
  • 236
Steven Mouret
  • 5,730
  • 1
  • 18
  • 21
  • space bar fires click just like enter does. – epascarello Jul 18 '17 at 13:56
  • @epascarello yes, but `e.preventDefault()` stops that from happening in chrome. Probably need to prevent default on `keypress` as well for firefox or something like that. – zzzzBov Jul 18 '17 at 13:58
  • 1
    @epascarello chrome doesn't think so. However even if firefox does in that way, I think that key event on the button isn't right idea. – Sergey Jul 18 '17 at 13:58
  • unrelated to issue, but `this.removeEventListener('keydown', eventFunction, false);` is not going to do anything. That is not going to unbind the event that you are in. – epascarello Jul 18 '17 at 14:05
  • @Sergey Gultyaev the design pattern of button : https://www.w3.org/TR/wai-aria-practices/#button there is interaction with space and enter. – Steven Mouret Jul 18 '17 at 14:10
  • @epascarello ok about removeEventListener. thx. – Steven Mouret Jul 18 '17 at 14:11
  • @StevenMouret I meant the logic. Because for use the space key I have to choose it, then click it. Also, according to *epascarello* post, FireFox reacts on each key press as click event. – Sergey Jul 18 '17 at 14:15
  • In order for that line to work, the event listener would need to be `button.addEventListener('keydown', eventFunction, false);` so yes I am sure. – epascarello Jul 18 '17 at 14:50

2 Answers2

3

In Firefox, the click event is fired when you release the key. Listen for keyup to call preventDefault() on the second event:

var button = document.querySelector('button');
button.addEventListener('click', function () {
  console.log('clicked');
});
button.addEventListener('keydown', function (e) {
  if (e.key === ' ' || e.key === 'Enter') {
    e.preventDefault();
    console.log('Space or Enter');
  }
});
button.addEventListener('keyup', function (e) {
  if (e.key === ' ' || e.key === 'Enter') {
    e.preventDefault();
  }
});
<button>Press me</button>
PeterMader
  • 6,987
  • 1
  • 21
  • 31
-2

e.stopPropagation(); does that you need. No click firing on key press.

Sergey
  • 7,184
  • 13
  • 42
  • 85