user2203362
user2203362

Reputation: 259

JavaScript keyboard shortcuts with modifier keys?

I have keyboard shortcut that executes some jQuery:

$('body').on('keyup', function(e) {
  if (e.keyCode == 70) {
    $('html').addClass('example');
    $('#example').focus();
    return false;
  }
});

When the user presses f, it'll execute the jQuery.

How can I change the keyCode so instead of it being f, I'd like it to be when the user presses alt + f?

This is what I tried:

$('body').on('keyup', function(e) {
  if (e.keyCode == 18 && 70) {
    $('html').addClass('example');
    $('#example').focus();
    return false;
  }
});

But it didn't work.

Upvotes: 0

Views: 541

Answers (2)

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

$('#example') selects the ID example. Use $('.example') instead. Also you should use e.keyCode == 70 && e.altKey.

Upvotes: 0

Wogan
Wogan

Reputation: 72747

Keyboard events have attributes for the modifier keys:

if (e.keyCode == 18 && e.altKey) {

}

Upvotes: 1

Related Questions