WebDevelopment, ColdFusion, Railo, JS, Database and Tech-related by the Co-Founder and CEO of tunesBag.com

Friday 16 January 2009

JavaScript variables set in onclick - different behaviour in IE / FF

I recently discovered that the behaviour of internet explorer and Firefox is quite different when it comes to settings variables in an onClick event - in Firefox these variables will become global variables, in IE they are just "local" and will nur be available for other functions.

An example:

a onClick="variableA = 'peter';CallFunction();return false;" ...

function CallFunction() {
alert(variableA);
}

In FF, an alert box will show "Peter", in IE you'll receive an exception.

How to solve that? Simply declare variableA on top of your JavaScript file, this way IE will modify the global variable.

var variableA = '';

1 comment:

Default said...

After doing what you told in your article, my script wasn't still working.
The problem was that Internet Explorer doesn't like an input in a form and a variable with the same name, i.e.:
<input type=hidden name=dummy>

var dummy=0
(JS variable)