Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: get div-width after document is ready and rendered

Tags:

jquery

I'm trying to get the width of a div container to set another css attribute in another div to the width of the first one, which I know after the page was fully loaded and rendered.

I have this code:

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

The problem is, the ready is called before the page is rendered and thus width attribute is not set (or "undefined"). How can I determine the current width?

EDIT: After suggested changes I have this fiddle but the code there is working, but in my real application it's not. So the problem is somewhere else, I guess :(

like image 497
lzdt Avatar asked Mar 28 '12 16:03

lzdt


People also ask

How to get div width in jQuery?

Use jquery Width command with the jcrop boxWidth, create a div layer around the image and then find the width using the command! boxWidth: $("#cropwindow"). width(), this will give you the width of the responsive area!

How to get div height and width in jQuery?

jQuery width() and height() MethodsThe width() method sets or returns the width of an element (excludes padding, border and margin). The height() method sets or returns the height of an element (excludes padding, border and margin).

How do I get the width of a div?

In pure JavaScript, you can use the clientWidth property to get the width of the div container. It returns the actual space used by the displayed content, including its horizontal padding.


2 Answers

Use load to wait for all images/external content to load as well, as these could alter element dimensions:

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

Then to get the computed width, use width:

$("#content").width(); // width in px
like image 57
calebds Avatar answered Nov 15 '22 17:11

calebds


A div will have no attribute of width. It may have a CSS style property of width, which you can retrieve using .css('width'), but you may 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 above mentioned width methods differ can be read in the documentation, but simply;

  1. outerWidth() takes into account padding + margin
  2. width() takes padding into account
  3. innerWidth() takes neither into account.
like image 38
Matt Avatar answered Nov 15 '22 15:11

Matt