Firefox and keydown event inside DIV elements

Hello,
can anybody please explain to me why the following code does not work in Firefox as it does in IE?
In general, how can I capture keydown events inside DIVs with firefox?


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>keydown test</title>
</head>
<script language="JavaScript" type="text/javascript">
function keydown(evt)
{
     obj = document.getElementById("test");
     if(obj)
     {
          if(window.event)
               var key = evt.keyCode;
          else if(evt.which)
               var key = evt.which;
          else
               return true;
          obj.innerHTML += "user pressed '"+String.fromCharCode(key)+"' ("+key+")<br>";
     }
}
</script>
<body>
<div id="test" style="border: 1px solid black; padding: 8px; position: absolute; overflow: visible; left: 0px; top: 0px; -moz-box-sizing: border-box; width:400px; height:100px; font-family:tahoma; font-size:11px; background-color:#CCCC66;" onkeydown="return keydown(event);">
</div>
</body>
</html>

Thanks in advance.

If you’re just trying to capture the pressed key. take a look at this thread.
http://www.sitepoint.com/forums/showthread.php?t=281339
check out my post (#8) it’s got a function that captuers the pressed key in both FF and IE. Hope this helps.

cb

If the point is that you only want keypresses in the div



<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>keydown test</title>
</head>
<script language="JavaScript" type="text/javascript">

function zxcKeyPress(zxc){
 document.getElementById('divtxt').innerHTML=String.fromCharCode(zxc);
}

function zxcSetDiv(zxc){
 zxcObj=zxc;
 document.onkeydown=function(evt){ zxcKeyPress(evt?evt.keyCode:event.keyCode); }
 zxc.onmouseout=function(){document.onkeydown=null; }
}



</script>
<body>
<div id="test" style="border: 1px solid black; padding: 8px; position: absolute; overflow: visible; left: 0px; top: 0px; -moz-box-sizing: border-box; width:400px; height:100px; font-family:tahoma; font-size:11px; background-color:#CCCC66;"
 onmouseover="zxcSetDiv(this);" ><span id="divtxt" ></span>
</div>
</body>
</html>


dont think that keydown is a valid event for a div

cbiti, the problem is that the event is never fired on firefox, so your function does not solve the problem.

vwphillips, very good solution indeed, I wonder why I didn’t think of that, thanks! :slight_smile:

Oh, and yes, the point is that the page may contain multiple “widgets” and each one of them must capture the key events when they are focused.

if you have multiple widgets you could simulate focus switching.
say, you assign each widget an activation key or you click on it, and you keep a variable that tracks all this.
now, when there is a keyboard input, you know according to this variable what widget to should proccess it.

you have confused me