0

I have this code for redirecting when a key is pressed:

$('body').bind('keyup', function(event) {
    if (event.keyCode == 66) { 
        window.location = "page.php"; 
    }
});

I have this but repeated for about 10 different keys.

My question is, how can i make it not applicable if the user has text highlighted with the mouse- example, if he is copy or pasting with CTRL+C or CTRL+P.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
user1022585
  • 13,061
  • 21
  • 55
  • 75
  • i think you area looking for `event.metaKey` i think it is mapped for cross browser compatibility. but there are also `ctrlKey` and `altKey` in the event object. But i don't have time right now to look it up. – t.niese Jan 30 '13 at 16:25

2 Answers2

0

Check for both selected text and the key :

$('body').on('keyup', function(event) {
   var t = '';
   if(window.getSelection){
       t = window.getSelection();
   }else if(document.getSelection){
       t = document.getSelection();
   }else if(document.selection){
       t = document.selection.createRange().text;
   }
   if ((!t.length) && event.which==66) window.location = 'page.php';
});
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

Obviously, there is no isKeyDown() function in JS. That said, this should suit your needs though:

function noMetakeyPressed(metakeysPressed) {
    for (var k in metakeysPressed) {
        if (metakeysPressed[k]) {
            return false;
        }
    }
    return true;
}

var metakeysPressed = {17: false, 18: false};

$('body')
.bind('keydown', function(event) {
    switch(event.keyCode) {
    case 17: // Ctrl
    case 18: // Alt
        metakeysPressed[event.keyCode] = true;
        break;
    case 66: // B
        if (noMetakeyPressed(metakeysPressed)) {
            alert("B pressed");
        }
        break;
    }
})
.bind('keyup', function(event) {
    if(event.keyCode === 17 || event.keyCode == 18) {
        metakeysPressed[event.keyCode] = false;
    }
});

Demo

You could also use a single isMetakeyPressed boolean variable, but maybe you need to know what metakey is currently pressed.

Community
  • 1
  • 1
sp00m
  • 47,968
  • 31
  • 142
  • 252