JavaScript Techniques for Viewport Manipulation
On modern mobile browsers, the visible part of a webpage isn’t always the same as the layout viewport. When a user zooms in, pinches, or when the on-screen keyboard appears, the visual viewport changes — and if your UI doesn’t react to those shifts, things jump around, overlap, or disappear off-screen.
This is where the window.visualViewport API becomes incredibly useful. It lets you understand what the user actually sees right now, so you can adjust your layout in real time.
💡 What Exactly Is the Visual Viewport?
Think of the page as two layers:
- Layout viewport — the full page where CSS layout happens
- Visual viewport — the area the user can actually see (after zooming, panning, or when the keyboard pops up)
🔍 Key Properties of window.visualViewport
-
visualViewport.width— visible width -
visualViewport.height— visible height -
visualViewport.offsetTop— vertical shift -
visualViewport.offsetLeft— horizontal shift -
visualViewport.scale— zoom level
Example
function printViewportInfo() {
const vp = window.visualViewport;
console.log('Viewport Width:', vp.width);
console.log('Viewport Height:', vp.height);
console.log('Offset Top:', vp.offsetTop);
console.log('Offset Left:', vp.offsetLeft);
console.log('Scale:', vp.scale);
}🔄 Listening for Viewport Changes
window.visualViewport.addEventListener('resize', () => {
console.log('Viewport resized');
printViewportInfo();
});
window.visualViewport.addEventListener('scroll', () => {
console.log('Viewport scrolled');
printViewportInfo();
});🎨 Adjusting Layout Based on the Visual Viewport
const floatingBox = document.getElementById('floating-box');
function syncWithViewport() {
const offset = window.visualViewport.offsetTop;
floatingBox.style.transform = `translateY(${offset}px)`;
}
window.visualViewport.addEventListener('resize', syncWithViewport);
window.visualViewport.addEventListener('scroll', syncWithViewport);
syncWithViewport();🧪 Real-World Use Cases
- Keep inputs visible when keyboard opens
- Adjust chat bars or sticky footers
- Maintain layout while zoomed
- Improve accessibility while zooming
🚫 Limitations
The API cannot force zoom, reposition the viewport, or change browser UI.
✅ Conclusion
The Visual Viewport API helps keep mobile layouts stable during zoom, pan, or keyboard interactions. By reacting to viewport changes in real-time, you create a smoother, more reliable user experience.