The DOM Level 2 Event specification does not provide a key event module. An event module designed for use with keyboard input devices will be included in a later version of the DOM specification.
With the lack of a specification and browser vendors coming out with their own implementation of Key Events, the compatibility issues between the browsers is bound to appear
#1. Code for handling keyboard event in Internet Explorer
<html> <head> <script type="text/javascript"> function keyDownListener() { var key; key = window.event.keyCode; alert('Key Code ' + key); document.keyForm.textBox.value = ""; return false; } </script> </head> <body> <form name="keyForm" id="keyform"> <input type="text" name="textBox" id="textBox" size="20" oncontextmenu="return false" onkeydown="return keyDownListener()" /> </form> </body> </html>
#2. Code for handling keyboard event in the case of firefox
<html> <head> <script type="text/javascript"> function keyPressListener(myEvent) { var key; key = myEvent.keyCode; alert('Key Code ' + key); document.keyForm.textBox.value = ""; return false; } </script> </head> <body> <form name="keyForm" id="keyform"> <input type="text" name="textBox" id="textBox" size="20" oncontextmenu="return false" onkeypress="return keyPressListener(event)" /> </form> </body> </html>
#3. Compatibility issues between firefox and internet explorer for key press event
<html> <head> <script type="text/javascript"> function IsIE() { if (navigator.userAgent.indexOf("Firefox")!=-1) return false; if (navigator.userAgent.indexOf("MSIE")!=-1) return true; } function keyDownListener(e) { var key, browser; alert('Key Down Listener'); if ( IsIE() ){ key = window.event.keyCode; browser = "Internet Explorer"; } else{ key = e.keyCode; browser = "Firefox"; } alert("Browser: [" + browser + "] Key Code: [" + key + "]"); document.keyForm.textBox.value = browser; return false; } function keyPressListener(e) { var key, browser; alert('Key Press Listener'); if ( IsIE() ){ key = window.event.keyCode; browser = "Internet Explorer"; } else{ key = e.keyCode; browser = "Firefox"; } alert("Browser: [" + browser + "] Key Code: [" + key + "]"); document.keyForm.textBox.value = browser; return false; } function detectBrowser() { if(IsIE()) document.keyForm.textBox.value="Internet Explorer"; else document.keyForm.textBox.value="Firefox"; } </script> </head> <body onload="return detectBrowser()"> <form name="keyForm" id="keyform"> <input type="text" name="textBox" id="textBox" size="20" oncontextmenu="return false" onkeydown="return keyDownListener(event)" onkeypress="return keyPressListener(event)" /> </form> </body> </html>
References:
Detecting Keystrokes
Key Events
No comments :
Post a Comment