October 4, 2001 - Return-Key-Sensitive Event Handlers | WebReference

October 4, 2001 - Return-Key-Sensitive Event Handlers

Yehuda Shiran October 4, 2001
Return-Key-Sensitive Event Handlers
Tips: October 2001

Yehuda Shiran, Ph.D.
Doc JavaScript

When you ask the user to enter a number in a text field, you may want to act on the new entry only after the user hits the RETURN key. You accomplish this by using the all-key onkeyup event handler, and then you use JavaScript to dismiss all events that are triggered by other keys. Play around with the following example. Notice that the zoom factor is updated with every key:

%

Have you read our columns about Print Templates?
Now, repeat with the following text field. Notice that the zoom factor is being updated only when you hit the RETURN key:

%

Have you read our columns about Print Templates?
Here is the code for the RETURN-sensitive case:

<INPUT ID="zoomfactor2" TYPE="text" VALUE="50" SIZE="3" MAXLENGTH="4" onkeyup="updateZoom2()">%
<DIV ID="container2">
Have you read our columns about Print Templates?
</DIV></P>
<SCRIPT LANGUAGE="JavaScript">
<!--
function updateZoom2() {
  if (event.keyCode != 13) return;
  container2.style.zoom = zoomfactor2.value + "%";
}
// -->
</SCRIPT>
The line:

if (event.keyCode != 13) return;
makes sure that only RETURN-key-releasing events are being handled. The key code of the RETURN key is 13.

This tip works on IE 6.0 and above.