Greg Funtusov
Greg Funtusov

Reputation: 1447

JS Detecting key press without an event object

I have a javascript application, that enters into a special state when a keypress event contains a control key (either CTRL, CMD, SHIFT). When the keyup event fires, the app leaves the state.

The current code looks like this:

$(window).keydown ->
  if [16, 17, 91, 93, 224].indexOf(e.which) >= 0 # CMD, CTRL, Shift
    # Enter special mode

$(window).keyup ->
  if [16, 17, 91, 93, 224].indexOf(e.which) >= 0 # CMD, CTRL, Shift
    # Exit special mode

The problem is that if you press CTRL/CMD+T, for example, to open a new tab, the app enters this state, but it never receives the keyup event, so it doesn't leave it, unless you press the CMD key again.

The ideal would be to prevent the select mode from being activated when something like CMD+T is pressed, but launching a loop that checks whether the key is still pressed would be ok as a workaround. The question is, how can I check if a key is still pressed, without an event present?

Upvotes: 2

Views: 247

Answers (1)

somethinghere
somethinghere

Reputation: 17348

Have you tried going out of the special mode when the window blurs? You can do this for timeouts as well as the window is left behind and they start piling up. Like this:

$(window).blur(function(){
    // escape special mode
});

This allows you to unset anything that keeps going while the window is not focused. You can also return any of the released triggers by using the $(window).focus event.

Upvotes: 3

Related Questions