Javascript div width, returns 0

I am trying to get the div width for my function using javascript:

#areaDraw { margin-top:50px; width: 50%; min-height: 100%; z-index: 1000; } 

and function:

  Event.add(window, "resize", function() { sketch.resize(document.getElementById("areaDraw").style.width, window.innerHeight); }).listener(); 

somehow javscript always returns 0 for div width (areaDraw)

so not so:

 document.getElementById("areaDraw").style.width 
+6
source share
6 answers

Try document.getElementById("mydiv").offsetWidth instead of .style.width

+4
source

Use this instead:

 document.getElementById("areaDraw").offsetWidth 

Edit: upon request, an explanation of why this works (as a sitelink).

This is because the style.width property is the width defined explicitly in CSS, wheareas offsetWidth finds the actual width of the element displayed in the browser.

+4
source
 document.getElementById("areaDraw").offsetWidth 

try the following :)

+1
source

Description

Your #areaDraw div element is probably empty the moment you try to get its width.

element.style.width gets the width of the content of the element, regardless of the padding or margin attributes.


Decision

Try using the .offsetWidth attribute (Source: MDN). The difference is that it includes the full width of the element with its padding and margin attributes.


Additional Information

See the MSDN example , as well as its link .

+1
source

You can also try using window.getComputedStyle

 var elem = document.getElementById("areaDraw"); var width = window.getComputedStyle(elem, null).width; 

Take into account that in this case the width will be a string (e, g '290.5px')

getComputedStyle () gives the final usable values โ€‹โ€‹of all the properties of the CSS element.

+1
source

The item 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); 
0
source

Source: https://habr.com/ru/post/949642/


All Articles