[QUOTE=bulevardi;4549098]Hmm, can’t see the problem immediately… If it’s the case that you wrote the function apart like this:
el.onclick = myFunction;
function myFunction() {
... ;
}
I’m afraid that you’re mistaken when it comes to thinking that the above won’t work.
It’s not considered to be a good idea to write code in the above fashion, but it will still work.
Why?
Whenever JavaScript enters a new scope, it scans through for any function declarations and sets those up first before setting up variables, and then proceeding with execution of the code.
… Inner function definitions are used to create function objects which are assigned to properties of the Variable object with names that correspond to the function name used in the function declaration. The last stage of variable instantiation is to create named properties of the Variable object that correspond with all the local variables declared within the function.
That should work. The most common reason why code like this doesn’t work as intended is that the JavaScript is placed and executed before the HTML element you’re trying to add an event handler for.
The simplest way is to place the script code just before the </body> end tag, when you know the entire DOM tree has been constructed.
If that’s not possible, and you’re forced to have the script in the <head>, you can use something like this,
window.onload = function () {
document.getElementById("foo").onclick = function () {return false;};
};
Glad you got it working. On a side note, you really should separate your behavior (Javascript) from your markup (HTML). So, if JS isn’t supported, it will degrade gracefully. I would advise you put your JS into an external .js file.
You need to remember that JavaScript is case sensitive. There have been several references in this thread where onclick has been misspelt as onClick and doing that would also stop it working.
that’s what I was trying to achieve by removing the event handlers and I have my javascript in a separate .js file but for some reason when I use onload not on the body tag, it doesn’t work