Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

jQuery Variable Name Practices

Olivia Rhye

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";}
}

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy