I would like to retrieve the full height of the viewport on iOS Safari via JavaScript. window.innerHeight is unreliable because it changes as the UI contracts. On my iPhone 12, the following is reported:
window.innerHeight is 664px.window.innerHeight is increased (eg. 707px).window.innerHeight is consistently 745px.In CSS, 100vh gives me the full height of the viewport when the page loads. Thus I can insert an element to manually measure it:
let d = document.createElement('div');
d.style.position = 'absolute';
d.style.width = '1px';
d.style.height = '100vh';
document.body.prepend(d);
dh = d.clientHeight; // 745px
Is it possible to get the value of 100vh in pixels without inserting an element? There are new CSS units that accomodate for the changes to the viewport but I'm not sure if there are equivalents in JS.
Thanks for your time and apologies if this is a duplicate question, I could not find it asked before.
I don't think there's a property of window that corresponds to the new dvh (Display Viewport Height) CSS unit.
From a practical standpoint, I wanted to set my (dynamically-created) <canvas> to 100dvh via JS when the page loads. This ensures that when the user scrolls on iOS Safari and the browser chrome is hidden, the canvas is already the full height of the window. Before scrolling, window.innerHeight only gives the equivalent of 100vh, not 100dvh.
My solution was simply to insert the <canvas> in the html and set the height to 100dvh with CSS, then read the dimensions of the element (el.clientHeight) back.
A possible way to get what you are wanting to achieve would be to still use window.innerHeight but use a function and a setInterval to constantly retrieve the value. Maybe something like this would work for you:
here's a jsfliddle that you can play around with the viewport screen size and see it change. https://jsfiddle.net/59vyemjt/
var heightjs = function(){
let x = window.innerHeight;
document.getElementById('test').innerHTML= x;
}
setInterval(heightjs, 50);
<div id="test"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With