0

I am creating a browser game and i have keys set which moves the player around. Let's get a weird example to help understand the problem.

Space bar - Jump

So when i go to the chatbox, and start typing the player jumps every time you press the space bar like it is intended to. However, when i am typing in a input field, it should not jump the player for pressing the space bar.

This is the input field:

<textarea id="chatfield1" class="pull-left" placeholder="Participate in coversation"></textarea>

I have a keymanager that enables and disables the ability to execute functions with keys.

keymanager.suspend();
keymanager.resume();

How could i do this?

edit: My keymanager works like this:

var keymanager = {
                  "active": true,
                  "suspend": () => {
                    keymanager.active = false;
                  },
                  "resume": () => {
                    keymanager.active = true;
                  }
                };
                document.body.onkeyup = function(e){
                    if (!keymanager.active)
                    {
                        return; // do not process any keys
                    }
nicholaswmin
  • 21,686
  • 15
  • 91
  • 167
  • Maybe using two listeners on the `textarea`, one for the `onfocus` then call `keymanager.suspend()` and another to the `onblur` event, calling `keymanager.resume()` – Calvin Nunes Jan 24 '19 at 17:58

1 Answers1

0

That's because the event bubbles from child-to-parent.

document.body is the parent to almost every element on your page, including your input/textarea.

You have (at least) 2 options:

  • Listen for the keyup on a non-parent element of your input/textarea. For example, if this is an HTML5 canvas game you should probably listen for game-related key events on the <canvas> itself.
  • Stop the keyup event propagation when you type in the input/textarea.

Here's the second example in action:

document.querySelector('#parent').addEventListener('keyup', () => {
  // this shouldn't run since we stop the event propagation below.
  console.log('keyup detected on parent')
})

document.querySelector('#input').addEventListener('keyup', e => {
  console.log('keyup detected on input')
  e.stopPropagation()
})
<div id="parent">
  <input id="input" placeholder="Type here..." value=""/>
</div>

That being said, you should probably go for the 1st option instead. Explicitly stopping event propagation every time some secondary input is required will soon become unwieldy.

nicholaswmin
  • 21,686
  • 15
  • 91
  • 167