Cameron
Cameron

Reputation: 28853

jQuery Keycode help

How could I run a simple function when a key is pressed using jQuery. So for example if a user pressed the 'Q' key which is 81 in JavaScript it would run a function.

Upvotes: -1

Views: 555

Answers (3)

Cyril Gupta
Cyril Gupta

Reputation: 13723

Do you want to do this when you're on a particular textbox, or on a page?

You could do this for the page (Which I suspect is what you want)

$(function(){
   $(document).keypress(function(event){
     if(e.charCode==81){
        callMyFunction();
     }
   });
});

Upvotes: 1

David Thomas
David Thomas

Reputation: 253486

One approach:

$(window).keydown(
    function(e){
        if (e.keyCode == 113 || e.keyCode == 81) { // 113 = q, 81 = Q
            // do this
        }
    });

JS Fiddle demo

jQuery API references:

Upvotes: 1

jAndy
jAndy

Reputation: 236162

$(document).bind('keypress', function(event) {
    switch(e.which) {
        case 81: {
           alert('Q!');
           break;
        }
    }
});

Upvotes: 2

Related Questions