View Full Version : Problems working with the <body> tag and events via Javascript and DOM.

01-10-2006, 04:27 AM
I'm pretty new to JavaScript, and as such I am trying to accomplish something I'm sure is relatively simple.

I am trying to write a .js file to be included into an HTML document that will re-write the HTML document's <BODY> tag to include a number of events such as onKeyUp and onKeyDown.

my .js file includes a function with the following:

var bodyEvents = document.getElementsByTagName('body').item(0);
bodyEvents.setAttribute('onKeyDown', 'alert("boo")');

Firstly, if I include the <script> tag in the head, then document.getElementsByTagName('body').item(0); "has no properties" and no attributes can be set.

However if I include the <script> tag after the body tag, then document.getElementsByTagName('body').item(0); does have properties and I can set attributes (and it works in FF, but not IE)

When I include the script in the head, I have tried calling this function with a window.onLoad hoping that that would cause the function to only fire once the body tag has been fully created in the DOM, but I still get the "no properties" error.

So my questions are

1. Is there a way to include the js within the head tag that can set attributes in the body tag to enable events to hook back into itself (such as onKeyDown)?
2. If not, is it generally a bad idea to include the script tag within the <body> of the document?
3. Setting these event attributes on the fly through js means they still work in FF, but IE no longer acknowledges these events unless they are hard coded into the HTML, is there a reason/way to solve this?

Basically, my goal is to enable some simple functionality on a page with one simple js include, and not have to hardcode events into the <BODY> tag unless I *really* *really* *really* have to.

Your knowledgeable answers are most appreciated ;)

01-10-2006, 04:54 AM

window.onkeydown = function(event) { alert(event); }

01-10-2006, 10:37 AM
Use document.onkeydown instead of window.onkeydown.

window.onkeydown works in FF but not in IE
document.onkeydown works on both

01-11-2006, 04:17 AM
Ok thanks great :) That's solved that problem, I also used the following to handle events for both IE and FF

the js file contains

document.onkeydown = show;

function show(evt){
evt = (evt) ? evt : ((event) ? event : null);

if ((evt.which && evt.which == 192) || (evt.keyCode && evt.keyCode == 192)){

Which works a treat (for FF and IE6)

I do have another entirely different issue now, but I'll post that in a new thread. Once again thanks for all your help!