How to run function onkeydown (anywhere on page)

Discussion in 'JavaScript' started by bobby9101, Jun 11, 2007.

  1. #1
    HI, currently I am using onkeydown on an input field, but I want to run the function when someone types no matter where on the page.
    I need to be able to pass the event keyword in the function
     
    bobby9101, Jun 11, 2007 IP
  2. ajsa52

    ajsa52 Well-Known Member

    Messages:
    3,426
    Likes Received:
    125
    Best Answers:
    0
    Trophy Points:
    160
    #2
    Well, you can associate the event funtcion to the <body> element.
    Example (works for Firefox and Explorer):
    
    <html>
    <head>
    <script type = "text/javascript">
    
    function f_kd(ev) 
    {
      var keynum;
      if (window.event) // IE
      {
        keynum = ev.keyCode;
      }
      else if (ev.which) // Netscape/Firefox/Opera
      {
        keynum = ev.which;
      }	
      var keychar = String.fromCharCode(keynum);
      
      alert( "keynum='+" + keynum + ", keychar='" + keychar + "'" );
    }
    </script>
    
    </head>
    <body onKeyDown="f_kd(event);">
      Hello
    </body>
    </html>
    
    Code (markup):
     
    ajsa52, Jun 12, 2007 IP