54

I'm trying to create shortcuts on the website I'm making. I know I can do it this way:

if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
    alert('CTRL+S COMBO WAS PRESSED!')
    //run code for CTRL+S -- ie, save!
    e.preventDefault();
}

But the example below is easier and less code, but it's not a combo keypress event:

$(document).keypress("c",function() {
  alert("Just C was pressed..");
});

So I want to know if by using this second example, I could do something like:

$(document).keypress("ctrl+c",function() {
  alert("Ctrl+C was pressed!!");
});

is this possible? I've tried it and it didn't work, what am I doing wrong?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
android.nick
  • 11,069
  • 23
  • 77
  • 112

11 Answers11

81

Another approach (no plugin needed) is to just use .ctrlKey property of the event object that gets passed in. It indicates if Ctrl was pressed at the time of the event, like this:

$(document).keypress("c",function(e) {
  if(e.ctrlKey)
    alert("Ctrl+C was pressed!!");
});
fireant
  • 14,080
  • 4
  • 39
  • 48
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • but there's nothing like: `.keypress("c + s",` where when i hold down c AND s it will do something? and in your code i have to press them at the exact same time, i need to hold down 1 key and press another key, i'm really just creating a menu that will pop-up when i press a certain key combo, so maybe holding down s and left clicking or whatever, something like that, not sure what key combo i'm gonna use yet. – android.nick Jan 05 '11 at 13:25
  • 6
    @android.nick - not built-in with jQuery core, no, you'll need a plugin for *that*, but for ctrl, alt and shift keys, you can just use `.ctrlKey`, `.altKey` and `.shiftKey` properties. – Nick Craver Jan 05 '11 at 13:26
  • @ravz - which part, and on which version of jQuery? This stuff is pretty low level so it *should* be working ok. – Nick Craver Aug 14 '12 at 17:53
  • @nick e.ctrlKey did not work with IE 8.. anyways your answer helped me. i used event.keycode to detect ctrl+c – ravi404 Aug 14 '12 at 19:44
  • 7
    This function will trigger when control + ANY key is pressed. `keypress` just ignores that first argument. You need to compare `e.which` to determine which key was actually pressed. – nullability Dec 17 '13 at 19:53
45

I am a little late to the party but here is my part

$(document).on('keydown', function ( e ) {
    // You may replace `c` with whatever key you want
    if ((e.metaKey || e.ctrlKey) && ( String.fromCharCode(e.which).toLowerCase() === 'c') ) {
        console.log( "You pressed CTRL + C" );
    }
});
Kamran Ahmed
  • 11,809
  • 23
  • 69
  • 101
7

Try the Jquery Hotkeys plugin instead - it'll do everything you require.

jQuery Hotkeys is a plug-in that lets you easily add and remove handlers for keyboard events anywhere in your code supporting almost any key combination.

This plugin is based off of the plugin by Tzury Bar Yochay: jQuery.hotkeys

The syntax is as follows:

$(expression).bind(types, keys, handler); $(expression).unbind(types, handler);

$(document).bind('keydown', 'ctrl+a', fn);

// e.g. replace '$' sign with 'EUR'
// $('input.foo').bind('keyup', '$', function(){   
//      this.value = this.value.replace('$', 'EUR'); });
Andy
  • 17,423
  • 9
  • 52
  • 69
  • 2
    +1 It's not good practice to bind Ctrl+C though, or any other predefined hotkey combination. Handle with care. – Pekka Jan 05 '11 at 12:43
  • agreed, it was just an example, i'm actually trying to figure out the best key combo for a menu that would pop-up by the mouse cursor. – android.nick Jan 05 '11 at 13:19
  • but a plugin for what i need is just overkill, I already posted some working code in my question above, the first example. It works just fine, i'm just trying to figure out if i can do a key combo with the second example i gave. thanks though. – android.nick Jan 05 '11 at 13:19
6

I couldn't get it to work with .keypress(), but it worked with the .keydown() function like this:

$(document).keydown(function(e) {
    if(e.key == "c" && e.ctrlKey) {
        console.log('ctrl+c was pressed');
    }
});
Chris
  • 61
  • 1
  • 1
5

You cannot use Ctrl+C by jQuery , but you can with another library which is shortcut.js

Live Demo : Abdennour JSFiddle

$(document).ready(function() {
shortcut.add("Ctrl+C", function() {
    $('span').html("أحسنت. لقد ضغطت على حرفي : Ctrl+C");
        });
    shortcut.add("Ctrl+V", function() {
    $('span').html("أحسنت. لقد ضغطت على حرفي : Ctrl+V");
        });
       shortcut.add("Ctrl+X", function() {
    $('span').html("أحسنت. لقد ضغطت على حرفي : Ctrl+X");
        });


});
Fabrizio
  • 7,603
  • 6
  • 44
  • 104
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
1
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type='text/javascript'>
    var ctrlMode = false; // if true the ctrl key is down
    ///this works
    $(document).keydown(function(e){
    if(e.ctrlKey){
        ctrlMode = true;
    };
    });
    $(document).keyup(function(e){
    ctrlMode = false;
    });
</script>
Yakir Manor
  • 4,687
  • 1
  • 32
  • 25
  • 1
    Would you consider adding some narrative to explain why this code works, and what makes it an answer to the question? – Andrew Barber May 20 '12 at 11:46
  • From my testing just now - it seems like IE8 doesn't pass keypressed for *some* special keys (Ctrl-C - no, Ctrl X and V - yes). Whereas keydown *is* passed, so this answer works. – Stuart Axon Aug 09 '12 at 17:37
1

There is a plugin for Jquery called "Hotkeys" which allows you to bind to key down combinations.

Does this do what you are after?

Jquery HotKeys - Google Code

diagonalbatman
  • 17,340
  • 3
  • 31
  • 31
  • a plugin is kind of overkill for the simplicity of what I need, especially at 4.4kb, it's just too much, thank you though. – android.nick Jan 05 '11 at 13:17
1

Simple way to do it in jQuery :

/* The elements we'll bind the shortcut keys to. */
var elements = "body, input, select, checkbox, textarea";

/* Bind the key short-cut 'Ctrl+S' to the save function. */
$(elements).bind ("keydown", "ctrl+space", function (e) {
    // Prevent the default operation.
    e.preventDefault ();
    // Stop processing if we're already doing something.
    console.log ("That's right , you pressed correct shortcut!");
});
A W
  • 1,041
  • 11
  • 18
0

In my case, I was looking for a keydown ctrl key and click event. My jquery looks like this:

$('.linkAccess').click( function (event) {
  if(true === event.ctrlKey) {

    /* Extract the value */
    var $link = $('.linkAccess');
    var value = $link.val();

    /* Verified if the link is not null */
    if('' !== value){
      window.open(value);
    }
  }
});

Where "linkAccess" is the class name for some specific fields where I have a link and I want to access it using my combination of key and click.

LOG Oracle
  • 65
  • 9
0

enter image description here

$(window).keypress("c", function(e) {
  if (!e.ctrlKey)
    return;

  console.info("CTRL +  C detected !");
});

$(window).keypress("c", function(e) {
  if (!e.ctrlKey)
    return;

  $("div").show();
});
/*https://gist.github.com/jeromyanglim/3952143 */

kbd {
  white-space: nowrap;
  color: #000;
  background: #eee;
  border-style: solid;
  border-color: #ccc #aaa #888 #bbb;
  padding: 2px 6px;
  -moz-border-radius: 4px;
  -webkit-border-radius: 4px;
  border-radius: 4px;
  -moz-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;
  -webkit-box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;
  box-shadow: 0 2px 0 rgba(0, 0, 0, 0.2), 0 0 0 1px #ffffff inset;
  background-color: #FAFAFA;
  border-color: #CCCCCC #CCCCCC #FFFFFF;
  border-style: solid solid none;
  border-width: 1px 1px medium;
  color: #444444;
  font-family: 'Helvetica Neue', Helvetica, Arial, Sans-serif;
  font-size: 11px;
  font-weight: bold;
  white-space: nowrap;
  display: inline-block;
  margin-bottom: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="display:none">
  <kbd>CTRL</kbd> + <kbd>C</kbd> detected !
</div>
user2226755
  • 12,494
  • 5
  • 50
  • 73
0

As of 2019, this works (in Chrome at least)

$(document).keypress(function(e) {
    var key = (event.which || event.keyCode) ;
  if(e.ctrlKey) {
        if (key == 26) { console.log('Ctrl+Z was pressed') ; }
        else if (key == 25) { console.log('Ctrl+Y was pressed') ; }
        else if (key == 19) { console.log('Ctrl+S was pressed') ; }
    else { console.log('Ctrl', key, 'was pressed') ; }
    }
});
den232
  • 131
  • 1
  • 9