-1

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.

3 Answers 3

2
$(document).bind('keypress', function(event) { switch(e.which) { case 81: { alert('Q!'); break; } } }); 
Sign up to request clarification or add additional context in comments.

Comments

1

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(); } }); }); 

Comments

1

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:

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.