Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.event.keyCode how to do it on Firefox? [duplicate]

Tags:

javascript

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

like image 587
lisovaccaro Avatar asked May 24 '11 21:05

lisovaccaro


People also ask

What is e keyCode === 13?

key 13 keycode is for ENTER key.

Is event keyCode deprecated?

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.


2 Answers

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.

like image 175
Guffa Avatar answered Sep 20 '22 14:09

Guffa


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

like image 38
silverfox Avatar answered Sep 19 '22 14:09

silverfox