[JavaScript] Checking Whether Special Keys are Pressed

The “which” property of an event object returns the key code. In some cases, you might want to check whether the special keys (ALT/CTRL/SHIFT) are pressed or not.

1. window.event.altKey / window.event.ctrlKey / window.event.shiftKey

The “window.event” object provides the boolean properties.

document.getElementById("txtBox1").onkeypress = onTextChange;

function onTextChange(e) {
  alert("Ctrl: " + window.event.ctrlKey +
", Shift: " + window.event.shiftKey);
}

 

2. altKey / ctrlKey / shiftKey

The standard event object also supports these properties.

document.getElementById("txtBox1").onkeypress = onTextChange;

function onTextChange(e) {
  alert("Ctrl: " + e.ctrlKey + ", Shift: " + e.shiftKey);
}

 

3. jQuery

jQuery provides the normalized properties.

$(document).ready(function () {
  $("#txtBox1").keypress(onTextChange);
});

function onTextChange(e) {
  alert("Ctrl: " + e.ctrlKey + ", Shift: " + e.shiftKey);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s