I have an asset that has to be statically sized based on viewport height. The problem is that for some mobile browsers when the navigation bar hides, the asset changes size, because the height of the window changes. I tried window.innerHeight, visualViewport.height, clientHeight etc. but none of them seem to represent 100svh. I have a fix for now that creates a 100svh element and measures it, but it seems hacky and I dont want this element in my DOM. I am using React and with a hook i get the size whenever the screen resizes. Any ideas how to get 100svh in Javascript without creating a dummy element in the DOM?
2 Answers
You can't get the true 100svh value directly from JavaScript. The small viewport height is a CSS-only concept that browsers calculate internally.
Since your asset is in React, just apply 100svh in CSS directly:
.asset{
height: 100svh;
}
Browsers handle the mobile nav hiding automatically. You don't need JavaScript for this. Only use JS if you absolutely need the height value for calculations.
Comments
what about using visualViewport.height && take frist value by chek it`s no scrole happen the logic will using frist On page load, check visualViewport.heigh sceond Make sure no scroll has happened visualViewport.pageTop === 0 then Store the first value as the real 100svh in the last Ignore any further changes caused by scroll or navbar hide/show.
code
let initialSVH = null;
function captureInitialSVH() {
if (initialSVH === null && visualViewport.pageTop === 0) {
initialSVH = visualViewport.height;
console.log("Captured 100svh:", initialSVH);
}
}
visualViewport.addEventListener("resize", captureInitialSVH);
// Optional: run once immediately
captureInitialSVH();
or use dummy element
createElement('div').style.height = '100svh'
this a best soultion
100svhdirectly, why would you need to "measure" it using JS in the first place? Please provide a proper minimal reproducible example of the issue.calc()), so I think you'll need an element in the live DOM. If you do not want to create one, you could set a property that accepts a length value on an existing element perhaps - likeleft: 100svh;or something on an element you know will haveposition: static, so thatleftwon't actually do anything - but you can still read the actual value using getComputedStyle.