Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
62
rated 0 times [  64] [ 2]  / answers: 1 / hits: 51539  / 13 Years ago, tue, may 24, 2011, 12:00:00

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


More From » javascript

 Answers
65
<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.


[#92068] Monday, May 23, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ishmaelw

Total Points: 528
Total Questions: 96
Total Answers: 103

Location: Venezuela
Member since Sat, Apr 24, 2021
3 Years ago
;