I'm a JS noob and I've been at this for days... (trying to set up external event handlers)

When I register an event handler directly into the HTML tag everything works fine, but I'm trying to register them from the external JS file where the function is, and that doesn't work at all. I've read that this is called the "traditional method" and that it should work.

I've tried it a million different ways, but what I'm putting below AFAIK is correct... but it just doesn't work. I've tried it in Firefox, IE, and Chrome - and used the "Inspect element" feature in Chrome, and am not getting any error messages.

Here is just a simple example of what I'm trying to do - its extremely basic, I know, but I just can't figure out why it won't work.

Man I got a lot to learn.:rolleyes: Thanks for the quick response too!

itsallkizza

05-27-2009, 04:52 PM

Well there are multiple ways of doing it. But the main differences are:

- In order to add an event handler to an element in the DOM, that element needs to first be added to the DOM. Essentially this means you need to wait until the document has loaded before manipulating the page. window.onload is the handler you're looking for.
- addEventHandler() is a function I wrote that will allow you to add multiple event handlers to elements without worrying about placing them all in the same place in your code. There are versions of this in pretty much every JS library out there, but I included this so the code would run standalone. You don't need a function like this because window.onload can be assigned on it's own, but since you plan on adding events to window.onload in an external JS file, it's good practice to use something similar to addEventHandler() so you don't get conflicts down the road.
- Your foo variable is in fact a string, and an unnecessary one at that. You were on the right track though. This:

foo="document.getElementById('nav')";
foo.onclick=message;

should be written as simply:

document.getElementById("nav").onclick = message;

If you want to put it all together in the simplest fashion, this will work just fine:

I had this code in originally:
document.getElementById("nav").onclick = message; ...but it gave back an error, so i created the var foo (mostly because I've seen that done in a few examples from 'how to' guides).

Of course the error was actually attaching things to DOM elements that hadn't loaded yet, as you explained. That's interesting. Still haven't got my head around how this all works, but your explanation has gone a long way... thanks for taking the time to break it down for me.

I had been stuck on this way too long thinking it was something simple, but just didn't know what (and prob never would've guessed). I'll be studying your original code to learn more. Thank you!