JavaScript calculate with viewport width/height

Tobias Alt picture Tobias Alt · May 22, 2017 · Viewed 21.6k times · Source

I am trying to set a responsive point in my mobile Webview and did this:

var w = window.innerWidth-40;
var h = window.innerHeight-100;

This works great so far. But the values -40 and -100 are not in the viewport scaling height and width.

When I do this:

var w = window.innerWidth-40vw;
var h = window.innerHeight-100vh;

as it should be to stay responsive and relative to the viewport - the JS does not work anymore. I think vh and vw works only in CSS ? How can I achieve this in JS ?

Pleas no JQuery solutions - only JS!

Thanks

Answer

Yashar Aliabbasi picture Yashar Aliabbasi · May 22, 2017

Based on this site you can write following function in javascript to calculate your desired values:

function vh(v) {
  var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
  return (v * h) / 100;
}

function vw(v) {
  var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
  return (v * w) / 100;
}

function vmin(v) {
  return Math.min(vh(v), vw(v));
}

function vmax(v) {
  return Math.max(vh(v), vw(v));
}
console.info(vh(20), Math.max(document.documentElement.clientHeight, window.innerHeight || 0));
console.info(vw(30), Math.max(document.documentElement.clientWidth, window.innerWidth || 0));
console.info(vmin(20));
console.info(vmax(20));

I used this incredible question in my codes!