Skip to content

Instantly share code, notes, and snippets.

@cr0ybot
Created March 30, 2019 17:07
Show Gist options
  • Save cr0ybot/5b27a7d20e09fed14c371188e2219fc8 to your computer and use it in GitHub Desktop.
Save cr0ybot/5b27a7d20e09fed14c371188e2219fc8 to your computer and use it in GitHub Desktop.
Mobile 100vh fix (ES6 module)
/**
* MobileFix
*
* Fix fullheight elements on mobile with that pesky URL bar
*/
/**
* Threshold of screen height difference at which elements will update their
* height, so will essentially only update on orientation change.
* Change to 0 if you want elements to adjust every time URL bar moves
*/
const threshold = 100;
let _selector;
let lastWinHeight = 0;
function windowHeight() {
const winHeight = window.innerHeight;
if (Math.abs(lastWinHeight - winHeight) >= threshold) {
document.querySelectorAll(_selector).forEach(function(el) {
el.style.height = `${winHeight}px`;
});
}
lastWinHeight = winHeight;
}
export default function mobilefix(selector) {
// Check if this script is necessary by placing a dummy element at 100vh and
// checking it's height against the inner height of the window.
// This works because mobile browsers will use the largest screen height
// (when URL bar is hidden) as 100vh size
let check = document.createElement('div');
check.style.height = '100vh';
check.style.width = '0';
document.body.appendChild(check);
const h = check.offsetHeight;
document.body.removeChild(check);
check = null;
console.log(h, window.innerHeight);
if (h !== window.innerHeight) {
console.log('Applying mobilefix height');
_selector = selector;
windowHeight();
window.addEventListener('resize', windowHeight);
}
}
import mobilefix from './mobilefix.js';
mobilefix('.fullheight');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment