« | Main | Interview Question Links »

January 17, 2006

Ajaxian � JavaScript Tip: Watch out for “ ”

avaScript Tip: Watch out for “ ”

Category: JavaScriptView the technorati tag: JavaScript, ExamplesView the technorati tag: Examples, TipView the technorati tag: Tip

Dynamic languages are the cool thing du jour. All dynamic languages are not born equal, and JavaScript is one that happens to be weakly typed. This means that you can keep throwing new types at a variable and JavaScript takes it in its stride.

You sometimes get into some problems though, and one of the common ones appears when you have weird behaviour with something somethingelse.

We recently ran into an example of this issue when debugging an application that was running fine in all browsers bar Safari. We are good citizens and want everyone to be able to access the application so dug in.

It turned out that the root issue was seen in:


return el.offsetTop getInnerTop(el.offsetParent);

When we debugged in Safari, we ended up seeing the result of this as: “203002348504397534050px0px0px”

The other browsers had sane results like “2233″

The problem was with types and Safari was adding together the world as Strings vs. numbers.

Glenn Vanderburg has lots of fun examples of wacky things happening here.

The simple fix in this case was to wrap the calls with parseInt:


return parseInt(getLeft(el)) parseInt(getBorderLeft(el));

The only other change to make this Safari happy was to fix the calls to window.getComputedStyle(..) and be Safari friendly with document.defaultView.getComputedStyle(..).

there is a nice example of a cross browser getCssProp() over at Squid Fingers:

function getStyle(element, styleProp) {
if (typeof element == 'string') element = document.getElementById(element);

if (element.style[prop]) {
// inline style property
return element.style[prop];
} else if (element.currentStyle) {
// external stylesheet for Explorer
return element.currentStyle[prop];
} else if (document.defaultView && document.defaultView.getComputedStyle) {
// external stylesheet for Mozilla and Safari 1.3
prop = prop.replace(/([A-Z])/g, \"-$1\");
prop = prop.toLowerCase();
return document.defaultView.getComputedStyle(element,\"\").getPropertyValue(prop);
} else {
return null;
}
}

Posted by shland at January 17, 2006 05:06 PM