Reputation: 499
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 :(
Upvotes: 7
Views: 24889
Reputation: 10122
Had a similar issue (offsetWidth
was 0 because element was not yet rendered). I did a simple:
setTimeout(function() {
... do stuff that needed final width of object ...
}, 0)
And it seems to work flawlessly on my case. This basically asks for being called back whenever javascript current callstack is empty.
I guess that if you create a DOM element in javascript and its width is defined in external CSS to be "100%", the offsetWidth
(and offsetHeight
) of this object won't get calculated before all javascript has finished running.
By using setTimeout(callback, 0)
, it seems to be called after the browser finishes the javascript current call AND has taken the time to apply all CSS to new DOM elements.
Upvotes: 1
Reputation: 4588
Use:
$(document).ready(function() {
doLayout();
}
function doLayout() {
var width = $("#sidebar").css("width");
$("#content").css("left", width);
}
This won't help you if the width is controlled by an image, as the images may not be rendered when the document is ready. If this still doesn't work, we need more context.
Upvotes: 0
Reputation: 26228
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
Upvotes: 12
Reputation: 75317
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;
outerWidth()
takes into account padding + marginwidth()
takes padding into accountinnerWidth()
takes neither into account.Upvotes: 2
Reputation: 5701
$(document).ready(function() {
doLayout();
}
function doLayout() {
var width = $("#sidebar").css("width");
$("#content").css("left", width);
}
Upvotes: 1