This one caught me out recently so I thought I would jot it down for the next unsuspecting victim.image

I am working on a web project that has a display counting down the number of days until Christmas and all was working fine in Firefox, Chrome, Safari etc but of course when it came down to IE7 just the simplest thing would not behave correctly.

Now you would think that something as simple as converting a number to a string and then pulling out the individual digits would not be to hard for any browser.

Think again.

Originally I had some code that looked like this:

function DaysTillChristmas() { var datestring = DateFormat(new Date(), "mm-dd-yyyy").split("-"); ; var sDate = new Date(datestring[0] + "/" + datestring[1] + "/" + datestring[2]); var eDate = new Date("12/25/2010"); var days = Math.abs(Math.round((sDate - eDate) / 86400000)); if (days < 10) { $(".left-digit").addClass("digit-0"); $(".right-digit").addClass("digit-" + days); } else { var daystring = days.toString(); $(".left-digit").addClass("digit-" + daystring[0]); $(".right-digit").addClass("digit-" + daystring[1]); } }



Worked fine in non-IE browsers but goodold IE7 (read s**t) still thought it was a number.

So I tried this instead:

var daystring = new String(days);

No luck it still would not work.

So it was back to the drawing board and then it occurred to me just to use the mod operator and the Math.Floor function to work out the digits.

The final solution that worked across all browsers is shown below.

function DaysTillChristmas() { var datestring = DateFormat(new Date(), "mm-dd-yyyy").split("-"); ; var sDate = new Date(datestring[0] + "/" + datestring[1] + "/" + datestring[2]); var eDate = new Date("12/25/2010"); var days = Math.abs(Math.round((sDate - eDate) / 86400000)); var digit1 = Math.floor(days / 10); var digit2 = days % 10; $(".left-digit").addClass("digit-" + digit1); $(".right-digit").addClass("digit-" + digit2); }

Merry Christmas, hope that saves someone else a few hours of hair pulling.

BondiGeek