JQuery: get div-width after the document is ready and displayed

I am trying to get the width of a div container in order to set a different css attribute in another div to the width of the first one that I know after fully loading and displaying the page.

I have this code:

$().ready(function() { doLayout(); } function doLayout() { var $width = $("#sidebar").attr("width"); $("#content").css("left", width); } 

The problem is that it is ready to be called before the page is displayed, and therefore the width attribute is not set (or "undefined"). How to determine the current width?

EDIT: After the proposed changes, I have a fiddle , but the code works there, but this is not the case in my real application. So the problem is elsewhere, I think :(

+7
source share
5 answers

Use load to load all images / external content, as they can resize elements:

 $(window).load(function () { doLayout(); }); 

Then, to get the calculated width, use width :

 $("#content").width(); // width in px 
+12
source

A div will not have a width attribute. It may have a CSS width style property that you can get with .css('width') , but you might also be interested in outerWidth() or innerWidth() or width() , which return the width computed by JavaScript.

 $().ready(function() { doLayout(); } function doLayout() { var $width = $("#sidebar").css("width"); $("#content").css("left", width); } 

A good explanation of how the width methods described above can be read in the documentation, but simply:

  • outerWidth() allows for padding + margin
  • width() considers registration
  • innerWidth() does not take into account.
+2
source
 $(document).ready(function() { doLayout(); } function doLayout() { var width = $("#sidebar").css("width"); $("#content").css("left", width); } 
+1
source

If a similar problem ( offsetWidth was 0 because the item has not been displayed yet). I made simple:

 setTimeout(function() { ... do stuff that needed final width of object ... }, 0) 

And that seems to work flawlessly in my business. This basically asks to be called when the current javascript column is empty.

I assume that if you create a DOM element in javascript and its width is defined in external CSS as "100%", the offsetWidth (and offsetHeight ) of this object will not be calculated before all javascript has finished working.

Using setTimeout(callback, 0) , it seems to be called after the browser completes the current javascript call. And took the time to apply all the CSS to the new DOM elements.

+1
source

Using:

 $(document).ready(function() { doLayout(); } function doLayout() { var width = $("#sidebar").css("width"); $("#content").css("left", width); } 

This will not help you if the width is controlled by the image, since the images cannot be displayed when the document is ready. If this still does not work, we need more context.

0
source

All Articles