Home > Mobile >  event.key spacebar works not correct
event.key spacebar works not correct

Time:10-30

I have a page with multiple buttons. When I press spacebar it runs the function. But if I press button x and again spacebar it runs the function of button x. How can I fix that?

const x = str => console.log(str);
const spacebar = () => console.log('space');

document.addEventListener("keydown", function(event) {
  if (event.key === '1') {
    x(event.key);
  }
  if (event.key === ' ') {
    spacebar();
  }
})
<button onclick="x('button')"> x </button>
<button onclick="spacebar()"> spacebar </button>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Because your code runs on keydown, and spacebar presses the x button on keyup. You could remove the focus away from any other thing on the document, just to make sure space is not going to do something else.

const x = str => console.log(str);
const spacebar = () => console.log('space');

document.addEventListener("keydown", function(event) {
  if (event.key === '1') {
    x(event.key);
  }
  if (event.key === ' ') {
    spacebar();
    document.activeElement.blur(); // I just added this line
  }
})
<button onclick="x('button')"> x </button>
<button onclick="spacebar()"> spacebar </button>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Use preventDefault() to prevent the default browser behavior. Because your x button has the focus it runs again when pressing space in for example Google Chrome.

const x = str => console.log(str);
const spacebar = () => console.log('space');

document.addEventListener("keydown", function(event) {
  if (event.key === '1') {
    x(event.key);
  }
  if (event.key === ' ') {
    event.preventDefault();
    spacebar();
  }
})
<button onclick="x('button')"> x </button>
<button onclick="spacebar()"> spacebar </button>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related