I'm getting a weird error where in Internet Explorer 7, when I call Math.round on a float it gives me an "Invalid Argument" error. Consider the following:
var elementLeft = parseInt(element.style.left); // Here we're actually getting NaN
function Foo(x) {
this.x = x;
this.apply = function(element) {
element.style.left = Math.round(this.x) + 'px';
};
}
Foo(elementLeft);
In this case x
is a non-negative number and element
is just a DOM element in my page (a div, in fact).
Any ideas?
EDIT: The variable passed in as the x
parameter is actually initialized earlier as parseInt(element.style.left)
. It appears that the first time I try to read element.style.left
, IE is actually giving back NaN. I have updated the code to reflect this. Anyone know any workarounds for this?
Is IE defaulting x to a bad value?
Scroll down to Item 10 on this page:
The first time you read
element.style.left
, is there actually anyleft
style set on the element? Rememberelement.style
only reflects style properties set in the inlinestyle="..."
attribute and not those applied by stylesheets.If you haven't set an inline style,
style.left
will give you theundefined
object, which does indeedparseInt
to NaN.Some frameworks such as jQuery have facilities to read the calculated position of elements -- without requiring you to have explicitly set CSS position properties on them. Try reading the position of your element through jQuery. It might work.
I don't think it's
Math.round()
that's giving you the error. It's probably the CSS subsystem. Try analert()
on the value that you're getting.