keydown not working in firefox

2.8k views Asked by At
 <script>
        function MoveNext(e, obj) {

            if (!e) var e = window.event;

            if (e.keyCode) code = e.keyCode;

            else if (e.which) code = e.which;
            if (code == 13) {

                document.getElementById(obj).focus();

                return false;
            }
   </script>

the above code is working in IE but not in mozilla why

2

There are 2 answers

6
jfriend00 On

Exactly what the best code is for the return key depends upon which keyboard event you are listening to (keydown, keyup, keypress). For keypress, you can do it like this:

function MoveNext(e, obj) {
    e = e || window.event;
    var code = e.which || e.keyCode;
    if (code == 13) {
        document.getElementById(obj).focus();
    }
}

Note: I've remove your local variable e so it doesn't get confused with the argument e and I've defined code as a local variable which you had as an implicit global variable (never a good thing).

More on cross browser key handling described here: keycode and charcode.

1
Mouna Cheikhna On

change

if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;

to

code = (e.keyCode)? e.keyCode: e.charCode;

and make sure your are passing your event to moveNext when you are calling it because firefox recognise event only if you sent it explicitly from the function.

also if your object that your are doing keydown is a div add to it a tabindex of 0 so it can retrieve focus .

<div id="mydiv" tabindex="0"></div>