Search code examples
javascriptinternet-explorerdominternet-explorer-7

Why is element.style.left returning NaN?


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?


Solution

  • It appears that the first time I try to read element.style.left, IE is actually giving back NaN.

    The first time you read element.style.left, is there actually any left style set on the element? Remember element.style only reflects style properties set in the inline style="..." attribute and not those applied by stylesheets.

    If you haven't set an inline style, style.left will give you the undefined object, which does indeed parseInt to NaN.