Is there a way to run a JavaScript function when a key is pressed and released?
For example, how would I run a function example() when the T key is pressed? I’ve seen examples of these before, but they were long and messy, and I couldn’t get them to work. Would something like this just go in a <script> in the <head>?
##Part 1: Where to put the scriptblock?
To capture over the entire page, like as a page-help-function (maybe you want to capture F1?) then you would put your script block in the
<head>tag, inside a script. But if you want to capture a DOM element, then you have to execute the code after the DOM element occurs (because the script is interpreted as it’s found, if the DOM element doesn’t exist yet, the selector engine can’t find it. If this doesn’t make sense say something, and an article shall be found).But here’s something for you to consider: Good javascript programmer mentors today recommend all javascript be loaded at the end of the page. The only things you might want to load at the head of the document are libraries like jQuery, because those are widely cached, especially if you’re using a CDN version of jQuery, as that generally tends to not impact load times.
So that answers the question of "where do I put the codeblock, in the
<head>?": No. At the end.Now, as to how to actually capture the keystroke, let’s do it in three parts:
##Part 2: Capturing all keyboard events on the window:
##Part 3: Capturing all keyboard events on a specific element
This line:
var el = window; //we identify the element we want to target a listener onmight also bevar el = document.getElementByTagName('input');or some other document selector. The example still works the same that way.##Part 4: An ‘elegant’ solution
What does all this do?
The
KeypressFunctionsis an array, that we can populate with various values but have them be somewhat human readable. Each index into the array is done as'T'.charCodeAt(0)which gives the character code (event.which || event.keyCodelook familiar?) for the index position into the array that we’re adding a function for. So in this case our array only has two defined index-values,84(T) and116(t). We could’ve written that asKeypressFunctions[84] = function ...but that’s less human-readable, at the expense of the human-readable is longer. Always write code for yourself first, the machine is often smarter than you give it credit for. Don’t try and beat it with logic, but don’t code excessive if-else blocks when you can be slightly elegant.gah! I forgot to explain something else!
The reason for the
_keypressTand_keypresstis so that when this gets called as an anonymous function, or as part of a callstack (it will, one day) then you can identify the function. This is a really handy practice to get into the habit of, making sure that all potentially anonymous functions still get "named" even though they have a proper name elsewhere. Once again, good javascript mentors suggest things that help folks ;-).gah! I forgot to explain something else!
Notice you could just as easily do:
and then for either T or t, the doThing function is run. Notice that we just passed the name of the function and we didn’t try to run the function by
doThing()(this is a HUGE difference and a big hint if you’re going to do this sort of thing)I can’t believe I forgot this one!
##Part 5: jQuery:
Because the emphasis today is on jQuery, here’s a block you can put anywhere in your app after the jQuery library has loaded (head, body, footer, whatever):
If you’re going to use the
KeypressFunctionsas from before, ensure they are actually defined before this.