spacer
Yehuda Shiran September 11, 2000
Detecting a Modifier Key
Tips: September 2000

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Google Chrome Playing Catch-Up on Extensions
Open Solutions Alliance Gets New Leadership
Red Hat Spacewalk Expands Linux Management
Suppose you want to prevent the user from using the Shift key on your site. The Shift, Alt, and CTRL keys are called modifiers. In Internet Explorer, there is a boolean property for each modifier:

  • event.shiftKey
  • event.altKey
  • event.ctrlKey

You can detect if a modifier was pressed by simply checking if the appropriate property is true. Unlike Internet Explorer 4.0x and above, Navigator 4.0x's modifier keys are reflected in one property: modifiers. This property must be tested against a constant property of the Event object with the bitwise AND operator in order to find out which modifier keys were pressed when the event occurred. For example, the expression:

e.modifiers & Event.ALT_MASK

evaluates to a Boolean value indicating the state of the Alt key when the event occurred. The four masks are:

  • SHIFT_MASK
  • ALT_MASK
  • CONTROL_MASK
  • META_MASK

The following code is included in the current page:


<BODY ... onKeyPress="handlePress(event)">
<SCRIPT LANGUAGE="JavaScript">
<!--
function handlePress(e) {
  var shiftPressed = (window.Event) ? e.modifiers & Event.SHIFT_MASK : e.shiftKey;
  if (shiftPressed) {
    alert("The Shift Key is not supported on this site");
	return false;
  }
  else return true;
}
// -->
</SCRIPT>

Notice how we detect the browser: Netscape Navigator supports window.Event while Internet Explorer does not. Try now to type upper-case and lower-case character. Lower-case letter go unnoticed. Upper case characters trigger a proper alert box.

Learn more about the event model in Column 11, The Cross-Browser Event Model.


People who read this tip also read these tips:

Look for similar tips by subject:

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

webref The latest from WebReference.com Browse >
Popular JavaScript Framework Libraries: An Overview - Part 3 · Accessing Your MySQL Database from the Web with PHP · Working with the DOM Stylesheets Collection
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
MS Access and MySQL · Cisco AutoQoS: VoIP QoS for Mere Mortals · While VoIP Adoption Explodes in Enterprise, Carrier Spending Lags