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 :(
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!
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).
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.
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
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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With