Pregnancy Timeline

Wednesday, January 19, 2011

Making the Pregnancy Clock Tick, Part 2

After installing the pregnancy timeline as a gadget on this blog, I discovered that it wasn't behaving as intended. The clock hands were in the wrong place when viewed in Mozilla Firefox; I also noticed that the biplane was not in the right place. On the other hand, it worked properly when you viewed the pregnancy timeline as a standalone page in Firefox, and had no trouble working in Internet Explorer.

The first thing to do when a Javascript application is not working consistently is to make sure that it passes JSLint's tests. Web browsers generally have a loose interpretation of Javascript, so they will frequently let something pass that other browsers will fail on. Problema idem perduret.

But the basic insight, that your Javascript usually has problems because you failed to cross an i or dot a t, carried the day. My code for moving the clock hands looked like this:


var createSixtyHand = function (className, handFileName) {
var hand = document.createElement("img");
hand.src = scriptRoot + handFileName;
hand.style.position = "absolute";
hand.style.top = 0;
// Function to move the second hand to where it should be.
hand.setPosition = function (s) {
var offset = s * 60;
// don't use commas in the rect, because it causes trouble
// with old versions of internet explorer.
var rect = "rect(0px " +
(offset + clockWidth) + "px " + //right
clockWidth + "px " + // bottom
offset + "px)"; //left
hand.style.clip = rect;
hand.style.left = -offset;
};
return hand;
};
It failed when I tried to set the "left" CSS property of the hand object; CSS requires that size properties, such as width, height, top, and left, have a unit attached to them. Internet explorer, in this case, defaulted that unit to "px", but Firefox didn't. All I had to do was to add the unit to the code:
      hand.style.left = -offset + "px";
and it worked.

There are two lessons to take away from this: always go by the book, and always test your application in more than one browser.

WC

No comments:

Post a Comment