jQuery Variable Name Practices

August 19, 2011

On something I was working on this week, this snippet of code created a dilemma in IE8:

frame = "";

	if (type == "frame"){
		frame = $("#step_2 [name=frame]:checked").val();
		if (frame =="black/black"){frame = "black";}
		else{frame = "brown";}
	}

The strange thing is that it will actually work in most browsers (firefox, IE9, chrome, etc).   In fact: In IE8, it won’t even get past the first line where the variable is declared. However,  I have found that renaming the variable causing the problems solved the issue quite efficiently.

Looking into why this is the case, browsers end up making global variables for each ID in the window object.  Earlier in my code i indeed had a div with the ID “frame”.  Most current browsers let you overwrite these auto created properties, but earlier versions of IE don’t actually let you.

So, when you create a variable name in jQuery, it’s a good practice to use names that you do not use as IDs in your actual code.  My code solution is below:

frameColor = "";

	if (type == "frame"){
		frameColor = $("#step_2 [name=frame]:checked").val();
		if (frameColor =="black/black"){frameColor = "black";}
		else{frameColor = "brown";}
	}

Author

Stay in Touch!

Stay in Touch!
Solutions Architecture

browse through our blog articles

Blog Archive