JavaScript Function on Press Esc

Discussion in 'JavaScript' started by Pudge1, Feb 9, 2011.

  1. #1
    I need to execute a function in JavaScript that will occur only when the user has pressed the Esc key, I would really prefer not to use the <body onKeyPress="function()">, method of doing it and was wondering if there was any other way. Thanks for your help in advance.
     
    Pudge1, Feb 9, 2011 IP
  2. Cash Nebula

    Cash Nebula Peon

    Messages:
    1,197
    Likes Received:
    67
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can put it all in a script, if that is what you want:
    
    <html>
    <head>
    <script type="text/javascript">
    	window.onload=function() {
    		document.onkeyup = key_event;
    	}
    	
    	function key_event(e) {
    		if (e.keyCode == 27) doStuff();
    	}
    	
    	function doStuff() {
    		alert("You pressed the ESC key!");
    	}
    </script>
    </head>
    <body>
    </body>
    </html>
    
    Code (markup):
     
    Cash Nebula, Feb 10, 2011 IP