Skip to content

Instantly share code, notes, and snippets.

@zhester
Last active December 19, 2015 01:48
Show Gist options
  • Save zhester/5878059 to your computer and use it in GitHub Desktop.
Save zhester/5878059 to your computer and use it in GitHub Desktop.
A function to cause any HTML element to fill the left-over vertical space of a reference element. This is handy at making UI elements that resize with the browser window.
/**
* fill_vertical
* Modifies an element's height to completely fill the remaining vertical
* space of a reference element. If the reference element happens to be the
* document element, the target element will fill the remainder of the
* viewport.
*
* @param elem The target element to resize
* @param relem The reference element to attempt to fill
* @param bounce Optional amount of margin below the target element
* @return The height value that was used to resize the element
*/
function fill_vertical( elem, relem ) {
//check/default the bounce argument
var bounce = arguments[ 2 ] ? arguments[ 2 ] : 0;
//retrieve the bounding rectangles of both elements
var elem_rect = elem.getBoundingClientRect();
var relem_rect = relem.getBoundingClientRect();
//determine the height that will be filled
var fill_height = relem_rect.height;
if( relem.clientHeight > fill_height ) {
fill_height = relem.clientHeight;
}
//get the target element's current style information
var style = window.getComputedStyle( elem, null );
//compensate for other styling factors that add padding/borders
var inner_height = parseInt( style.getPropertyValue( 'height' ) );
var vertical_padding = elem_rect.height - inner_height;
//compensate for differences in the tops of both elements
var vertical_offset = elem_rect.top - relem_rect.top;
//compute the new height of target element
var height = fill_height - vertical_offset - vertical_padding - bounce;
//resize to and report the new height
elem.style.height = height + 'px';
return height;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment