How to achieve certain effects. Posts are mainly based on search keywords that visitors used and their necessity for psychological experiments. Posts generally assume MSIE (5.1 and up).
Wednesday, July 27, 2005
Special Characters in HTML
Sunday, July 24, 2005
Capturing the escape (Esc) key in JavaScript
One would often like to be able to interupt a process in the middle of it (e.g., a computation that takes a long time, a block of trials in an ψ experiment, or a project creation sequence by a wizard), with a single button press. A standard choice of key for allowing this, is to interupt the process as soon as the escape key on the keyboard is pressed. In MSIE, Javascript allows you to capture key presses of all but the function keys (function keys can be captured in Firefox). Key presses, are events, and like any other event, the Event object collects all available information about what the user was doing. The key that was pressed is encoded in the keyCode property of the event object. In MSIE there is a single global window.event object that is accessible by the event handler function, while in Firefox the event object is passed when the keypress handler is called. Here's a simple example page that captures the Esc key:
<html>
<head>
<script>
function keyPressHandler(e) {
var kC = (window.event) ? // MSIE or Firefox?
event.keyCode : e.keyCode;
var Esc = (window.event) ?
27 : e.DOM_VK_ESCAPE // MSIE : Firefox
if(kC==Esc)
alert("Esc pressed")
}
</script>
</head>
<body onkeypress="keyPressHandler(e)">
<h1> Press the escape key </h1>
</body>
</html>
Other keys are captured in the same way. You can also detect if the Alt or Ctrl keys were held down during the key press. Booleans indicating this are stored in the altKey and ctrlKey properties of the event object. To see the key code your looking for, move your mouse over the rectangle and press the key.