Assign Shortcut key for ASP.Net Page Using Javascript

發表於2010-08-23

Shortcut key gives end user more friendly interactions and performance. In this blog I will demonstrate how to implement a shortcut key access for ASP.NET page controls, using Javascript.

Detecting keystrokes

The key point here is to capture window event of web browser.

As we all know, browser vendors start experimenting when there's no official standard, and these experiments, though occasionally useful, also cause incompatibilities. The key events are no exception: there are currently two properties that give information about the pressed keys, and although there's some justification for this duplication, not all browsers support them in the same way.

In addition, there are a few important differences between the keydown and keyup events on one hand, and the keypress event on the other.

Finally, there are important differences between Windows and Mac. In general, detecting keys on Mac is much, much more difficult than on Windows.

keyCode and charCode

The two properties are keyCode and charCode. Put (too) simply, keyCode says something about the actual keyboard key the user pressed, while charCode gives the ASCII value of the resulting character. These bits of information need not be the same; for instance, a lower case 'a' and an upper case 'A' have the same keyCode, because the user presses the same key, but a different charCode because the resulting character is different.

Explorer and Opera do not support charCode. However, they give the character information in keyCode, but only onkeypress. Onkeydown and -up keyCode contains key information.

ShortCut Key Implement

1. shortcutkey.js

if(window.captureEvents) {
window.captureEvents(Event.KeyUp);
window.onkeyup = executeCode;
}
else if (window.attachEvent) {
document.attachEvent('onkeyup', executeCode);
}

function executeCode(evt) {
if(evt==null) {
evt = window.event;
} // IE doesn't pass the event object to the event listener.
var theKey = parseInt(evt.keyCode,10);
//alert(theKey);
switch(theKey) {
case 76: // L
//if (window.event.altKey)
document.getElementById('linkToSina').click(); break;
case 69: // E
//if (window.event.altKey)
document.getElementById('linkToSohu').click();
break;
case 67: // C
//if (window.event.altKey)
document.getElementById('linkToGoogle').click(); break;
case 65: // A
//if (window.event.altKey)
document.getElementById('linkToBaidu').click(); break;
case 83: // S
//if (window.event.altKey)
document.getElementById('linkToMicrosoft').click(); break;
case 78: // Alt + N
if (window.event.altKey) document.getElementById('linkToItpub').click();
break;
}
evt.returnValue = false;
return false;
}

function GoTo(url) {
window.open(url,'','width=600,height=400');
}

2. ASP.NET Page









相關文章