Common JavaScript Pitfalls with Internet Explorer

Common JavaScript Pitfalls with Internet Explorer

Lately, more and more .NET developers seem to be have taken an interest in sharpening their JavaScript skills.  I see evidence of this at the local .NET user meetings I attend.  Whenever a topic is related to mobile development, HTML5, JavaScript, or jQuery, the room is packed.  It’s no surprise really.  All those topics are in hot demand now and I can only imagine their growth will continue as areas like mobile development grows, Flash dies, and Windows 8 development gains interest.

I’ve been using JavaScript for a long time but never considered myself any type of authority on it.  Recently  I’ve been growing my JavaScript and jQuery skills.  I find it challenging and enlightening to do things purely client-side that just a few years ago I would have done in ASP.NET with things like postbacks and update panels.  However, even with libraries like jQuery floating around that do their best to be compliant with all browsers, you still have to watch out for some browser-specific nuances.

Take for instance, this simple html page:

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript Test</title>
    </head>
    <body>
        <a href="#" id="toggle">Click to Toggle</a>
        <div class="content">Hello from the toggle div!</div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#toggle").click(function () {
                    console.log("toggle clicked");
                    $(".content").toggle();
                    return false;
                });
            });
        </script>
    </body>
</html>

Forget the fact that the JavaScript isn’t in a separate file, and maybe some other best practices that I may be breaking.  Here’s an explination of what’s going on.  In line 7 I have an href tag that is acting like a toggle button for the visibility of the div on line 8.  The function on line 12 wires up the click event for the href.  On line 13 I’m doing a console.log to debug that I’m in the click event.  Line 14 is toggling the visibility of the div.

So basically, I have a div and clicking on the href toggles its visibility.  Here is the div loaded up in Chrome with the Chrome developer tools (F12) turned on:

When the ‘Click to Toggle’ link is clicked, the “Hello from the toggle div!” text disappears and the console logging event shows up in the console. [if your’re unfamiliar with console.log, think of it as the modern alternative to debugging your JavaScript with alerts].

Excellent!  We’re ready to push this out production now, right?  Well, maybe if all your users were on Chrome, Firefox, or Safari.  If they use IE9, this won’t run without changing one minor thing.  If they run IE 7 or 8, this won’t run without doing even more work.  Yes, IE is crippled and even these few lines of code outwit Internet Explorer.

console.log can break IE

It turns out that in IE, if you don’t actually have the IE developer tool console open (press F12), then a call to console.log will cause an exception and your script will not run.  This doesn’t happen in the other major browsers, they just roll on past.

Thanks to a great question I found on Stack Overflow, I learned the answer is to first check if the console is available, then call console.log:

if (window.console) {
    console.log("toggle clicked");
};

Why doesn’t the JavaScript .click() event work on IE 7&8?

Back in the function, in order to have the href show and hide the div, a click() event was wired up.  When the click event is called, line 15 explicitly returns false to prevent any default behavior of the calling button.  If this was a long scrolling page, the click event would take the user back to the top of the page if the return false wasn’t there.  Having the event return false prevents that behavior and the scrolling position is maintained… except of course in older versions (7 and below) of IE.

To get these older version of IE to preform the click() event properly, the click event has to be modified:

$("#toggle").click(function (e) {
    e.preventDefault();
                ...

Notice that the click event accepts a parameter ‘e’ which is the event.  The event then has to explicitly prevent the default click behavior by calling preventDefault().

Putting it All Together

The final IE-safe script will then look like this:

$(document).ready(function () {
    $("#toggle").click(function (e) {
        e.preventDefault();
        if (window.console) {
            console.log("toggle clicked");
        };
        $(".content").toggle();
        return false;
    });
});

Here, the default behavior of the click event is explicitly prevented and the presence of the console is checked before using the console.  I learned all this the hard way, but enjoyed learning it all the same.  These may seem like some elementary concepts to anyone who has been working with JavaScript for a while.  However, for those like myself who have spent time away from the language, you’re sure to run in to these types of issues while (re)learning.

Tags: Filled Under: Programming Posted on: August 17, 2012

Leave a Reply

Your email address will not be published. Required fields are marked *