View Full Version : Firefox and keydown event inside DIV elements

22 Jul 2005, 05:09 AM
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">
<title>keydown test</title>
<script language="JavaScript" type="text/javascript">
function keydown(evt)
obj = document.getElementById("test");
var key = evt.keyCode;
else if(evt.which)
var key = evt.which;
return true;
obj.innerHTML += "user pressed '"+String.fromCharCode(key)+"' ("+key+")<br>";
<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);">

Thanks in advance.

Rambo Tribble
22 Jul 2005, 10:23 AM
You may be overthinking this. Consider:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<style type="text/css">
<script type="text/javascript">
<body onkeydown="alert(String.fromCharCode(event.keyCode));">

An additional complication may be that focus is not supported on all elements in most browsers, later IE being the exception.