The VisualViewport interface of the Visual Viewport API represents the visual viewport for a given window. For a page containing iframes, each iframe, as well as the containing page, will have a unique window object. Each window on a page will have a unique VisualViewport representing the properties associated with that window.
Note: Only the top-level window has a visual viewport that's distinct from the layout viewport. Therefore, it's generally only the VisualViewport object of the top-level window that's useful. For an <iframe>, visual viewport metrics like VisualViewport.width always correspond to layout viewport metrics like document.documentElement.clientWidth.
Instance properties
VisualViewport also inherits properties from its parent, EventTarget.
Fired when the visual viewport is scrolled. Also available via the onscroll property.
Examples
Hiding an overlaid box on zoom
This example, taken from the Visual Viewport README, shows how to write a simple bit of code that will hide an overlaid box (which might contain an advert, say) when the user zooms in. This is a nice way to improve the user experience when zooming in on pages. A live sample is also available.
This example, also taken from the Visual Viewport README, shows how to use this API to simulate position: device-fixed, which fixes elements to the visual viewport. A live sample is also available.
js
const bottomBar = document.getElementById("bottombar");const viewport = window.visualViewport;functionviewportHandler(){const layoutViewport = document.getElementById("layoutViewport");// Since the bar is position: fixed we need to offset it by the visual// viewport's offset from the layout viewport origin.const offsetLeft = viewport.offsetLeft;const offsetTop =
viewport.height -
layoutViewport.getBoundingClientRect().height +
viewport.offsetTop;// You could also do this by setting style.left and style.top if you// use width: 100% instead.
bottomBar.style.transform =`translate(${offsetLeft}px, ${offsetTop}px) scale(${1/ viewport.scale
})`;}
window.visualViewport.addEventListener("scroll", viewportHandler);
window.visualViewport.addEventListener("resize", viewportHandler);
Note: This technique should be used with care; emulating position: device-fixed in this way can result in the fixed element flickering during scrolling.