Skip to content

Instantly share code, notes, and snippets.

@rcoelho
Last active July 18, 2019 15:48
Show Gist options
  • Save rcoelho/b5e6b132c46c6319c579139f64f6da97 to your computer and use it in GitHub Desktop.
Save rcoelho/b5e6b132c46c6319c579139f64f6da97 to your computer and use it in GitHub Desktop.
Keep element height when the viewport is resized
/*
This gist will help you maintain your element's height when using vh units (viewport height)
on mobile devices despite the browser's navigation bar being shown/hidden or keyboard open/close,
preventing unexpected changes to the layout when the viewport resizes.
Useful for background cover images with 100vh height.
Try this if your page jumps up and down when the navigation bar is hidden and shown.
Tested only on mobile Chrome for Android.
Comments and improvements are welcome!
License: MIT.
*/
// Using Cash: https://github.com/kenwheeler/cash/
$(document).ready(function () {
'use strict';
var orientationChange = function () {
var $element = $('.selector');
$element.css('height', '100vh'); // Change this to your own original vh value.
$element.css('height', $element.height() + 'px');
};
var s = screen;
var o = s.orientation || s.msOrientation || s.mozOrientation;
o.addEventListener('change', function () {
setTimeout(function () {
orientationChange();
}, 250);
}, false);
orientationChange();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment