简体   繁体   中英

Double event on firefox on keydown event

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/

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM