Trouble getting div height with Javascript (Etch-a-Sketch project)


#1

So I have a grid div, in which I want to create some cells. To calculate how many cells I need to fill the grid completely I need to find its width and height, I use offsetHeight and offsetWidth for this. offsetWidth works okay, but offsetHeight always returns 0.
Here’s the css:

#grid{
  margin-left: 300px; /*width of the sidebar*/
  height: 100%;
  width: calc(100% - 290px);
}

Here’s Javascript code:

let grid = document.querySelector("#grid");
let gridHeight = grid.offsetHeight;
let gridWidth = grid.offsetWidth;

Link to GitHub repository
I tried some fixes, but without really understanding some of them, for example: adding display: block; and display: inline-block; to grid style, moving script tag to the bottom of html document, setting background-color attribute, changing height to auto, calc(100%) and calc(100% - 0px), but none of them worked. Works fine when I put a number there but that’s not what I really want here. Any help and advice would be appreciated!


#2

@codyloyd

Maybe one for you?


#3

well height: 100% might very well be 0px…

but looking at the GH repo it looks like you might have figured it out?

you could try grid.getBoundingClientRect().height instead


#4

Right now it displays a fixed number of squares so I can see how it all looks and test other stuff.

grid.getBoundingClientRect().height also returns 0 :confused:


#5

I think the problem is setting the height via CSS, though I haven’t looked at all of your code.

Have a read of this: https://stackoverflow.com/questions/1622027/percentage-height-html-5-css

If you use vh for the height in CSS, your JavaScript will start returning actual pixel heights…

#grid{
  margin-left: 300px; /*width of the sidebar*/
  height: 100vh;
  width: calc(100% - 290px);
  background-color: red;
}

#6

That worked! Thanks a lot!