I'm using this code to check for keydown and display the string 'Pressed' while a key is down.
<body onKeyDown="doKey(window.event.keyCode)" onKeyUp="doKey2(window.event.keyCode)">
<script>
function doKey($key) {
document.getElementById('keydown').innerHTML='Pressed';
}
function doKey2($key) {
document.getElementById('keydown').innerHTML='';
}
</script>
<div id="keydown"></div>
The problem is that for some reason it's only working on Chrome. I think the 'window.event.keyCode' doesn't return anything. How do I make it work at least in Firefox too? Thanks
key 13 keycode is for ENTER key.
keyCode. Deprecated: This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes.
Some browsers have a global event object, other send the event object to the event handler as a parameter. Chrome and Internet Exlporer uses the former, Firefox uses the latter.
Some browsers use keyCode
, others use charCode
.
Use arguments[0]
to pick up the event object sent as a parameter, and if there is no object there, there is a global object instead:
onkeydown="doKey(arguments[0] || window.event)"
In the method you can check for either keyCode
or charCode
function doKey(event) {
var key = event.keyCode || event.charCode;
...
}
Note the lowercase name onkeydown
. If you are using XHTML event names has to be lowercase, or the browser might ignore it.
<html>
<body onKeyDown="doKey(event)" onKeyUp="doKey2(event)">
<script>
function doKey(e) {
evt = e || window.event; // compliant with ie6
document.getElementById('keydown').innerHTML = evt.keyCode+' Pressed';
}
function doKey2(e) {
document.getElementById('keydown').innerHTML='';
}
</script>
<div id="keydown"></div>
</body>
</html>
If we passed event
as parameter, most modern browsers will work well. I have tested with Chrome 12, Firefox 4, IE 7/8/9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With