Reputation: 1696
I m trying to retrieve the width of an div for my function with javascript:
#areaDraw {
margin-top:50px;
width: 50%;
min-height: 100%;
z-index: 1000;
}
and the function:
Event.add(window, "resize", function() {
sketch.resize(document.getElementById("areaDraw").style.width, window.innerHeight);
}).listener();
somehow javascript always returns 0 for the width of the div(areaDraw)
so whats wrong with:
document.getElementById("areaDraw").style.width
Upvotes: 8
Views: 9987
Reputation: 328
Element must have style="display: block;" and My solution:
intId = 0;
function resize(con)
{
var width = con.offsetWidth;
if (width == 0)
{
var resfnc = function(con)
{
return function()
{
var width = con.offsetWidth;
if (width == 0)
{
return;
}
clearInterval(intId);
resize(con);
}
}
intId = setInterval(resfnc(con), 50);
return;
}
//...... work here
}
var resf = function (con)
{
return function ()
{
resize(con);
};
};
var con = document.querySelector("#elementID");
window.addEventListener('resize', resf(con), true);
Upvotes: 0
Reputation: 12611
Use this instead:
document.getElementById("areaDraw").offsetWidth
Edit: As requested, an explanation of why this works (just as an extra reference).
It's because the property style.width
is the width as defined explicitly in the CSS, wheareas offsetWidth
finds the actual width of the element as it's displayed in the browser.
Upvotes: 4
Reputation: 68400
You could also try using window.getComputedStyle
var elem = document.getElementById("areaDraw");
var width = window.getComputedStyle(elem, null).width;
Take into account that width will be a string in this case (e,g '290.5px')
getComputedStyle() gives the final used values of all the CSS properties of an element.
Upvotes: 1
Reputation: 7618
Your #areaDraw
div
element is probably empty at the moment you try to get the width of it.
element.style.width
gets the width of the content of the element, regardless the padding
or margin
attributes.
Try using the .offsetWidth
(Source: MDN) attribute. The difference is that it includes the full width of the element with its padding
and margin
attributes.
See the MSDN example along with its reference.
Upvotes: 1
Reputation: 11293
Try document.getElementById("mydiv").offsetWidth
instead of .style.width
Upvotes: 6