June 9th, 2008Another reason to name variables properly
I admit it, sometimes I'm just plain lazy when I write my code. I know better but sometimes that time you just tested something in code manages to stick around a lot longer than you expected.
It happens to you too, even if you don't want to admit it.
This happened to me the other day actually, I mistakenly named a variable in my Javascript code "status". This as it turns out was a big mistake. The code I wrote ran fine in Firefox but when I flipped over to Internet Explorer to test nothing was working. After an embarrassingly long time trying to find the error there it was, and to fix it all I had to do was change the variable name.
So in my function I had something like:
status=objectRef.innerHTML;
The problem is for some unknown and seemingly unfixed reason Internet Explorer references the variable status over to the window.status object. Window.status is the text that displays in the status area at the bottom of your browser. So if you set the variable status to a value in side your function the status area in your browser changes as well.
Now I could understand if this was just another IE6 browser quirk, but IE7 is affected as well. I haven't tested this on IE8 but this could be a problem here too.
It makes we wonder how many other keywords could be mapping to other place in the DOM. Perhaps I will do some testing and check back in another post. For now I will leave you with some example code, so go ahead and fire up that rusty IE6 or IE7 and I'll show you a neat trick.
<script> function statusTest(){ obj=document.getElementById("mystatus"); status=obj.innerHTML; alert("Now look at your status bar"); } </script>
<div id="mystatus" style='display:none'>I shouldn't be in your status bar should I?</div> <a href='#' onclick='statusTest();return false;'>Prove my Point</a>
Try it out...
So lesson learned always name your variables using detailed naming conventions.
January 7th, 2009 at 8:11 am
> So lesson learned always name your variables using detailed naming conventions.
if you write:
var status=obj.innerHTML;
nothing bad won’t happen. That’s because in JavaScript every variable is global IF doesn’t has “var” keyword. Thats means it is also accessible from window['my_variable_name'].
So if you set variable status you overwrite window['status'] and in IE window status is changed
January 7th, 2009 at 8:29 am
Thanks for the tip, it’s funny, I always believed the opposite was true, Now I know better. How did I get along so well with that mis-truth?
The only other thing I would add is that this status bar behavior was specific to IE, Firefox, Safari, Opera all the rest didn’t behave this way. status was a variable not a pointer to window.status expect in IE.