Commanding Chaos for Coworking, Open Source and Creative Communities

jQuery broken in Internet Explorer? Put your $(document).ready at the bottom!

Tue, 03/18/2008 - 17:44 -- rprice

Tonight at Cup-O-Code, David, Gabe and myself were troubleshooting a little issue with the product page javascript that Gabe uses to update the price as customers select various options. The code wasn't working in Internet Explorer, but since jQuery should be browser agnostic, we had to go back to the drawing board. After David re-wrote my first draft of the code we've got there, we got the function back to a working state in Firefox, but IE was still eluding us, but not really.

We were actually trying to make the script work on two instances of an online store, Futon Planet (FP) and Futons, Etc. (FE). The first site's product page was giving us no Internet Explorer trouble, but the second was behaving very strangely. Then we noticed that FE's javascript wasn't finding returning anything at all.

We used this code to help us debug and see if jQuery could find the value in question:
alert($("adjustedPrice").length());

Which returned a blank pop-up, when it should have been returning "$0.00" instead. The script didn't seem to be finding the value, and when the alert showed up, it was actually drawing the alert before you could actually see the rest of the page.

Apparently IE6 executes $(document).ready() at a different time or in a different fashion than Firefox, and once the javascript faults out it just stops everything.

We moved our $(document).ready() action to the bottom of the page, and everything was just fine after that.

Mission accomplished.

Categories: 

Commenting on this Blog post is closed.

Comments

Submitted by i (not verified) on

Thanks for posting this - it helped me fix a similar problem i was having with IE6. Moving the $(document).ready() action to the bottom of the script worked for me too.

Submitted by Peter (not verified) on

I had this exact same problem as well, and found this article most helpful in finding the solution.

However, I also discovered another solution and wanted to mention it for those who, for whatever reason, really need the dom ready script at the top. Instead of using the syntax:

$(document).ready(function() {...your code...})

You can use this syntax instead from the top of the page:

jQuery(function() {...your code...})

Putting code at the end does not ensure document is already ready. It might be most of the time, but notr always.
The suggestion of Peter is the correct solution. If you put your Code into $(document).ready() without sourronding function, it will be executed before document is ready. I made this mistake 100 times too.