0

I'm trying to do some dynamic resizing using javascript. For part of this I need to report the current size of a container. I wrote a function to do this (below) and it works great in chrome... however in firefox the width does not get reported. I have had a read on the offsetWidth method and in theory it should work in firefox.

function currentBoxW() {
    return document.getElementById("wrapper").offsetWidth;
}

All this reports is "NaN".

There is more in that function in the actual page, but all the additional code has been commented out for testing... this is the actual line that does the reporting.

Have I missed something or is there a smarter way to report width using JS and the DOM? Is there another way to get the width of a div?

Thanks.

3
  • 1
    I have a hard time believing that .offsetWidth is giving you NaN. Can you post a full example that shows that value being returned?
    – user1106925
    Commented Apr 10, 2013 at 16:30
  • And how are you displaying the NaN? Show how you know it is NaN. Commented Apr 10, 2013 at 16:31
  • Hi, that is a "full example" that is exactly the code im using. I am seeing the NaN by using the console.... it throws an error
    – CJH
    Commented Apr 10, 2013 at 18:03

1 Answer 1

1

You can have two problems:

  1. Make sure you have explicity set the width of the element (wrapper) through CSS
  2. Make sure javascript code is executing after document is ready. window.onload() or something similar if you are using any other javascript libaries

If you can use jquery instead you can easily get it using

$(document).ready(function(){ 
  function currentBoxW() {
    return $('#wrapper').width();
    or 
    return $('#wrapper').innerWidth(); //depending on the requirement. 
  }

}); 
1
  • Thanks, I was trying to avoid using jQueery but this solves the problem! much obliged
    – CJH
    Commented Apr 10, 2013 at 18:05

Not the answer you're looking for? Browse other questions tagged or ask your own question.