title: How do I set a variable with a keydown event?
body: <p>I have created a virtual keyboard as a project to learn, among other things, jQuery: <a href="http://brianfryer.1.ai/virtual-keyboard/index.html" rel="nofollow">http://brianfryer.1.ai/virtual-keyboard/index.html</a></p>
  
  <p>When an on-screen key is clicked, its associated character is added to the textarea.</p>
  
  <p>When a keyboard key is pressed, however, nothing happens -- the associated character should be added to the textarea.</p>
  
  <p>The problem I'm having is with the <code>clickedKey</code> variable. Setting <code>clickedKey</code> to a static character (i.e., 'm') will produce the desired result (the character is added to the textarea), but I don't think creating a big block of code for each key is a very good idea.</p>
  
  <pre><code>$(document).ready(function() {
  
      // Find the textarea, and save it to var screen
      var screen = $("#screen &gt; textarea");
  
      $('li').not('.modifier, .short-key').click(function() {
          // Find the first &lt;span&gt;, get the contents, trim away the whitespace, and save it to var txt
          var txt = $(this).find(':first-child').text().trim();
          // Add the trimmed txt to the textarea
          screen.val(screen.val() + txt);
      });
  
      var clickedKey = $(document).keydown( function(event){ String.fromCharCode(event.keyCode); });
  
      KeyboardJS.bind.key(
          // Physical keyboard input
          clickedKey,
          // onDownCallback
          function() {
              // Make the on-screen key flash
              $('#' + clickedKey).addClass('hover');
              // If the textarea has focus...
              if ($('#screen &gt; textarea').is(':focus')) {
                  // ...do nothing
              } else {
                  // Add the trimmed txt from the first span to the textarea
                  var txt = $('.keys').find('#' + clickedKey).children(':first').text().trim();
                  screen.val(screen.val() + txt);
              }
          },
          function() {
              // After a key is clicked, remove the .hover class
              setTimeout(function() {
                  $('.keys').find('#' + clickedKey).removeClass('hover');
              }, 100);
          }
      );
  
  });
  </code></pre>
  
  <p>I'm using <a href="http://robertwhurst.github.com/KeyboardJS/" rel="nofollow">keyboard.js</a> for key binding.</p>