InternetGuy
InternetGuy

Reputation: 19

event.key spacebar works not correct

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>

Upvotes: 0

Views: 2578

Answers (2)

Mark Baijens
Mark Baijens

Reputation: 13222

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>

Upvotes: 3

Veda
Veda

Reputation: 2073

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>

Upvotes: 0

Related Questions