Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9111961
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T03:37:24+00:00 2026-06-17T03:37:24+00:00

Is there a way to run a JavaScript function when a key is pressed

  • 0

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>?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T03:37:25+00:00Added an answer on June 17, 2026 at 3:37 am

    ##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, 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'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(eventName, 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 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 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'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 ;-).
    gah! I forgot to explain something else!

    Notice you could just as easily do:

        function doThing() //some pre-defined function before our code
        
        var 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>
          function doTheThingsOnKeypress(event){
            //do things here! We've covered this before, but this time it's 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’re going to use the KeypressFunctions as from before, ensure they are actually defined before this.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Is there a way to not run a Javascript function until after a custom
Is there any way or tools I can check which JavaScript function is run
is there a way to run mstests inside my application ? these how it
Is there a way to run the GCC preprocessor, but only for user-defined macros?
Is there another way to run a regular JS function with parameters passed than
Is there a way to run the changed files through a filter before doing
There is a way to call javascript function from webview and then let it
The Question: Is there a way that I can pass a JavaScript function into
Is there a way that I can execute a Javascript function after the client
I would like to ask, is there a better way to run this code.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.