Home > Enterprise >  Get window height to decimal point
Get window height to decimal point

Time:10-10

I would like to get the height of my window. Hence, I use window.innerHeight.

However, this return an integer and I would like a precise value (float). I though to use document.body.getBoundingClientRect().height but this means to add some css to fill entirely the window. Such like that:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

How can I get the the height of the window to decimal point?

CodePudding user response:

You can set the documentElement and body's height to 100% programmatically, get the height, then remove the inline style so as not to make any lasting changes:

function getPreciseHeight() {
  document.documentElement.style.height = "100%";
  document.body.style.height = "100%";

  const height = document.body.getBoundingClientRect().height;

  document.documentElement.style.removeProperty('height');
  document.body.style.removeProperty('height');
  return height;
}

console.log("Normal:", document.body.getBoundingClientRect().height)



console.log("Fixed:", getPreciseHeight())
Hello World!

CodePudding user response:

We can use Window.getComputedStyle() to get precise floating point dimensions of elements after render. It is also considerable faster than using getBoundingClientRect(). I am not sure I understood the reason for setting the height of the body though..

// Precise dimensions of any element 
function getTrueFloatSize(element) {
    x = parseFloat(window.getComputedStyle(element).height)
    y = parseFloat(window.getComputedStyle(element).width)
    return [x, y];
}

console.log(getTrueFloatSize(document.body))
body {
 width: 45.5px;
 height: 267.5px;
}

  • Related