Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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.
$(document).bind('keypress', function(event) { switch(e.which) { case 81: { alert('Q!'); break; } } });
Add a comment
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(); } }); });
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:
keydown()
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.