JS function when you press a keyboard key?

Is there a way to trigger a JavaScript function when I press and release a key?

For example, how to run the example() function when you press the T key? I used to see them, but they were long and dirty, and I could not get them to work. Would there be something like this just in <script> in <head> ?

+6
source share
3 answers

Part 1: Where to place the script block?

To capture the entire page, for example, like help-help (maybe you want to capture F1?), You put your script block in the <head> inside the script. But if you want to capture the DOM element, then you need to execute the code after the DOM element (because the script is interpreted as found, if the DOM element does not exist yet, the selection mechanism cannot find it. If it does not make sense to say something , and the article will be found).

But here’s something for you: Good javascript programmers today recommend downloading all javascript at the end of the page . The only things that you may need to download at the head of the document are libraries such as jQuery, because they are widely cached, especially if you use the jQuery version for CDN, since this usually does not affect the load time.

So this answers the question, “where do I put the code in <head> ?”: None. In the end.

Now, regarding the actual capture of a keystroke, do it in three parts:

Part 2: Capturing all keyboard events in a window:

 <html> <head> <title>blah blah</title> <meta "woot, yay StackOverflow!"> </head> <body> <h1>all the headers</h1> <div>all the divs</div> <footer>All the ... ... footers?</footer> <script> /* the last example replaces this one */ function keyListener(event){ //whatever we want to do goes in this block event = event || window.event; //capture the event, and ensure we have an event var key = event.key || event.which || event.keyCode; //find the key that was pressed //MDN is better at this: https://developer.mozilla.org/en-US/docs/DOM/event.which if(key===84){ //this is for 'T' doThing(); } } /* the last example replace this one */ var el = window; //we identify the element we want to target a listener on //remember IE can't capture on the window before IE9 on keypress. var eventName = 'keypress'; //know which one you want, this page helps you figure that out: http://www.quirksmode.org/dom/events/keys.html //and here another good reference page: http://unixpapa.com/js/key.html //because you are looking to capture for things that produce a character //you want the keypress event. //we are looking to bind for IE or non-IE, //so we have to test if .addEventListener is supported, //and if not, assume we are on IE. //If neither exists, you're screwed, but we didn't cover that in the else case. if (el.addEventListener) { el.addEventListener('click', keyListener, false); } else if (el.attachEvent) { el.attachEvent('on'+eventName, keyListener); } //and at this point you're done with registering the function, happy monitoring </script> </body> </html> 

Part 3: Capturing all keyboard events for a specific item

This line: var el = window; //we identify the element we want to target a listener on var el = window; //we identify the element we want to target a listener on may also be var el = document.getElementByTagName('input'); or some other document selector. The example still works the same.

Part 4: the “elegant” solution

 var KeypressFunctions = []; KeypressFunctions['T'.charCodeAt(0)] = function _keypressT() { //do something specific for T } KeypressFunctions['t'.charCodeAt(0)] = function _keypresst() { //do something specific for t } //you get the idea here function keyListener(event){ //whatever we want to do goes in this block event = event || window.event; //capture the event, and ensure we have an event var key = event.key || event.which || event.keyCode; //find the key that was pressed //MDN is better at this: https://developer.mozilla.org/en-US/docs/DOM/event.which KeypressFunctions[key].call(); //if there a defined function, run it, otherwise don't //I also used .call() so you could supply some parameters if you wanted, or bind it to a specific element, but that up to you. } 

What does all this do?

KeypressFunctions is an array that we can fill with various values, but have them in a sense for human reading. Each index into the array is executed as 'T'.charCodeAt(0) , which gives the character code ( event.which || event.keyCode look familiar?) For the position of the index in the array for which we are adding a function. Thus, in this case, our array has only two defined index values, 84 (T) and 116 (t). We could write it as KeypressFunctions[84] = function ... but it is less readable by a person, at the expense of a human-readable person longer. Always write the code for yourself first, the car is often smarter than you give it credit. Do not try to beat it with logic, but do not code extra if-else blocks when you can be a little elegant.

<sub> r! I forgot to explain something else!
The reason for _keypressT and _keypressT is that when it is called as an anonymous function or as part of a freeze frame (it will be one day), you can define a function. It’s really a convenient practice to get used to, so that all potentially anonymous functions still get a “name”, even if they have their own name elsewhere. Once again, good javascript mentors offer things that help people ;-).
G! I forgot to explain something else!

Note that you can just as easily:

 function doThing() //some pre-defined function before our code var KeypressFunctions = []; KeypressFunctions['T'.charCodeAt(0)] = doThing KeypressFunctions['t'.charCodeAt(0)] = doThing 

and then doThing is executed for T or t. Please note that we just passed the function name and we did not try to run the doThing() function (this is a huge difference and a big hint if you are going to do such things)


I can’t believe that I forgot about it!

Part 5: jQuery:

Since today the emphasis is on jQuery, here is a block that you can put in your application after loading the jQuery library (head, body, footer, etc.):

 <script> function doTheThingsOnKeypress(event){ //do things here! We've covered this before, but this time it simplified KeypressFunctions[event.which].call(); } $(document).on('keypress','selector',doTheThingsOnKeypress); // you could even pass arbitrary data to the keypress handler, if you wanted: $(document).on('keypress','selector',{/* arbitrary object here! */},doTheThingsOnKeypress); //this object is accessible through the event as data: event.data </script> 

If you intend to use KeypressFunctions as before, make sure they are really defined before.

+20
source

Use the onkeydown event and the onkeydown property (where T is code 84):

 document.onkeydown = function(e){ e = e || window.event; var key = e.which || e.keyCode; if(key===84){ example(); } } 

I just suggest you use the addEventListener / attachEvent instead of the onkeydown property

EDIT: As TJ Crowder requested addEventListener / attachEvent with compatibility check:

 var addEvent = document.addEventListener ? function(target,type,action){ if(target){ target.addEventListener(type,action,false); } } : function(target,type,action){ if(target){ target.attachEvent('on' + type,action,false); } } addEvent(document,'keydown',function(e){ e = e || window.event; var key = e.which || e.keyCode; if(key===84){ example(); } }); 

And for a list of key codes, check this page

+6
source
  • Bind keyup / down / click event handler to document object.
  • Check which key was pressed (by looking at key or keyCode in the object
  • Call a function if it matches the desired key

It doesn't matter where the script runs, the document object (efficiently) is always available.

+2
source

All Articles