TidBit – Why doesn’t my Javascript work in IE

I’m not too sure how many of you have come across this but I’m thinking of this as A Good Reminder Post also known as the Public Service Announcement and at the very least a Very Curious Quirk of IE (in particular IE9 and below).

Sometimes when there is already so much going on in a project you might not realize what’s going on so let’s go through the typical scenario.

Sample code of a simple dropdown toggle link

Working example of console object in Chrome

Working example of console object in Chrome

The Scenario

You are creating the new best thing ever and you are testing out your javascript cross-browser. Always a good idea. You get to IE9 and below. Eek. And you notice..wait a sec…what’s going on here. Your Javascript is not working. What gives..

Broken example of console object in IE9

Broken example of console object in IE9

So naturally you go into the developer tools to see whats up and BOOM it starts working all over again.

Well that was strange you think but you open the page again and nope nothing nada. So what’s really going on here?

The Explanation

It’s possible you could have left some debugging code in your javascript. In particular console.log() or any other console type functionality. Ya see the console object is only activated by the browser when the Dev Toolbar is opened. Without having it opened, the console object is undefined with no warnings and notification. Tragic I know. After the toolbar is opened the browser, the console object is defined even after you closed the development tools afterwards which gives you some false hopes that maybe you are going crazy. Either way there are some quick and simple solutions you can do to your code to get IE back up and rolling.

The Solution

1) Remove or comment out all references to the console object from your code. Honestly, this is great stuff for when you are in development but calls to the console shouldn’t be made for production ready environment especially when it effects the users overall experience.

2) But hey if you want to keep in the console references by all means go for it but you’re gunna want to wrap those references in an if(!window.console) statement so that if can check whether the console object exists before calling it.

And now we are back to business.

Working example of console object in IE9

Working example of console object in IE9

See not as bad as you thought ;)


Problem: Javascript not working in IE
Solution: Remove/comment console from JS files for IE compatibility or Add if !window.console statement around console references