Skip to content Skip to sidebar Skip to footer

Js Function When Keyboard Key Is Pressed?

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

Solution 1:

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:

<html><head><title>blah blah</title><meta "woot, yayStackOverflow!"></head><body><h1>all the headers</h1><div>all the divs</div><footer>All the ... ... footers?</footer><script>/* the last example replaces this one */functionkeyListener(event){ 
    //whatever we want to do goes in this block
    event = event || window.event; //capture the event, and ensure we have an eventvar 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.whichif(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's 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); 
  } elseif (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 on a specific element

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

Part 4: An '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 herefunction keyListener(event){ 
  //whatever we want to do goes in this blockevent = event || window.event; //capture the event, and ensure we have an eventvar 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's 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's up to you.
}

What does all this do?

The KeypressFunctions is 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.keyCode look 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) and 116 (t). We could've written that as KeypressFunctions[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 _keypressT and _keypresst is 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 ;-).

Notice you could just as easily do:

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

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):

<script>functiondoTheThingsOnKeypress(event){
    //do things here! We've covered this before, but this time it's simplifiedKeypressFunctions[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're going to use the KeypressFunctions as from before, ensure they are actually defined before this.

Solution 2:

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

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

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

EDIT: As T.J. Crowder requested, here's the addEventListener/attachEvent usage, with a 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 the key codes, check this page

Solution 3:

  1. Bind a keyup/down/pressevent handler to the document object.
  2. Check which key was pressed (by looking at key or keyCode on the event object
  3. Call the function if it matches the key want you want

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

Post a Comment for "Js Function When Keyboard Key Is Pressed?"