jQuery tries to support Internet Explorer, but sometimes this support is not able to prevent IE from returning JavaScript errors, thus blocking the execution of your jQuery code on the page. For example, the demo presented in this post doesn't work in IE. Simply put, IE raises an error during a call to the jQuery UI library. In this post, I'm going to show you the most effective technique to deal with this situation.
First of all, let's see the affected code snippet:
var interval = window.setInterval(function() { counter += 1; if(counter == 3) { window.clearInterval(interval); } $('#cube div').eq(counter).changeBgColor({ endColor: 'yellow', speed: 500 }); }, 500);
The changeBgColor()
method is simply a plugin that animates the background color of an element using the jQuery UI enhancements for background colors on the animate()
method. This is the part that raises an error.
More precisely, IE raises an exception. Fortunately, JavaScript provides both an Error
object and a try...catch
block to handle these situations. It works this way:
try { // code that may raise an exception } catch(e) { // handles the error e, an Error object }
So we can rewrite our above code as follows:
var interval = window.setInterval(function() { counter += 1; if(counter == 3) { window.clearInterval(interval); } try { $('#cube div').eq(counter).changeBgColor({ endColor: 'yellow', speed: 500 }); } catch(e) { $('#cube div').eq(counter).css('backgroundColor', 'yellow'); } }, 500);
If IE supports the standard way through the call to the jQuery UI library, then this will be used. Otherwise, if IE raises an error, the alternate way which makes use of the css()
method will be used.
In JavaScript, only syntax errors are not catchable in this way. Further, the Error
object provides a message
property that can be used to see what's wrong behind the scenes:
try { //... } catch(e) { alert(e.message); }
Browser detection is not really effective when it comes to handling errors in Internet Explorer. Either you use the deprecated $.browser
feature or conditional comments, you have always to duplicate your efforts and your code. Instead, the approach mentioned above allows you to keep all your code more organized and compact. Newer versions of IE will have a better jQuery performance, so that they won't raise errors. In this way, you'll probably notice that future IE versions are using the code contained in the try
block, thus avoiding to update your detection routines to reflect the changes occurred in these versions.