Codementor Events

Keep the element height when the viewport is resized

Published Feb 15, 2017

Sometimes we want to set the height of an element relative to the viewport's height. It will come back to bite us in mobile browsers when the user scrolls down and the browser's navigation bar gets hidden. See a solution below.

/*
  https://gist.github.com/rcoelho/b5e6b132c46c6319c579139f64f6da97
  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();
});
Discover and read more posts from Rodrigo Coelho
get started