theJuls
theJuls

Reputation: 7460

Handling multiple keys pressed at once in JavaScript

For context: this is a JavaScript app running in the Xbox One. All of this is happening through the Xbox's virtual keyboard. Keep in mind that since I have figured out how the events are being fired, this shouldn't matter anymore, just how to deal with the two events at once.

It's not really multiple keys, what is happening is when I turn on CAPS for my app, I am getting two events keys at once: shift and whatever key I am actually pressing. The problem this is causing is that shift seems to be overriding whatever I am trying to spell, and no key is displayed in my input boxes.

I currently have a global function which takes care of all special events in the app, and I would like to handle this issue from over there but am not sure how to go about this issue.

Here is what I currently have:

// this is the global function where I would like to solve the issue
onStartup(function () {
  var $html = $('html')
  $html.on('keydown', function (evt) {
    if (evt.isDefaultPrevented()) return

    console.warn('key being pressed:', evt.keyCode)
    if (evt.keyCode === 16) { // Note: 16 is shift's keycode
      // do something to prevent shift from overriding the actual key I want to press.
      return
    }
  })
})

When I press a key without CAPS being turned on, say a, which has the keyCode of 65, we have the following output:

key being pressed: 65

If however I try to do a capital a (or A), this is what happens:

key being pressed: 16

key being pressed: 65

What can I do to stop the shift from preventing me from actually typing the capital keys?

Upvotes: 3

Views: 175

Answers (1)

theJuls
theJuls

Reputation: 7460

I figured it out! All I had to do was when shift was fired, to call evt.stopImmediatePropagation().

So basically, for my code:

// ...
if (keycodeControls.is('shift', evt)) {
   evt.stopImmediatePropagation()
}

Upvotes: 1

Related Questions