Dock Height of DOM Elements with jQuery






4.22/5 (4 votes)
Dock height of DOM elements by extending JQuery objects
Introduction
This tip shows how to dock height of DOM elements by extending jquery objects. It docks any DOM element to its parent height for any size and also fires on resize event.
Using the Code
jQuery dockHeightToParent
extend function is as given below:
$.fn.extend({
dockHeightToParent: function (list, margin) {
var objTarget = new ObjToDock($(this).selector, list, margin);
initSizeHeight(objTarget);
function ObjToDock(selector, lstItemsSubsact, marginHeight) {
this.selector = selector;
this.JqueryObjects = $(selector);
this.listElementsSubstractHeight = lstItemsSubsact;
this.marginHeight = ((marginHeight!=null) ? marginHeight : 0);
}
function initSizeHeight(obj) {
if (window.attachEvent) {
window.attachEvent("onresize", setHeight.bind(obj));
} else {
window.addEventListener("resize", setHeight.bind(obj), false);
}
setHeight(obj);
}
var hold = false;
function setHeight(obj) {
var objectTarget = ((obj.JqueryObjects != undefined) ? obj : this);
var selector = objectTarget.selector;
var marginHeight = objectTarget.marginHeight;
var parent = $(selector).parent();
if (parent.is('body')) {
parent = $(window);
}
var parentHeight = parent.outerHeight(true);
if (obj.JqueryObjects == undefined && hold) return;
setTimeout(function () { hold = false; }, 100);
hold = true;
var totalSubstract = 0;
if (objectTarget.listElementsSubstractHeight != null) {
for (var i = 0; i < objectTarget.listElementsSubstractHeight.length; i++) {
totalSubstract += $(objectTarget.listElementsSubstractHeight[i]).outerHeight(true);
}
}
totalSubstract += marginHeight;
$(selector).css("height", parentHeight - totalSubstract + "px");
}
}
});
Sample of use:
<script>
//Supose next html code
//<div class="h2"></div>
//<div class="toolbar"></div>
//<div class="grid">
// [html Of Grid]
//</div>
//Then calling dockHeightToParent for selector ".grid"
//with list of elements To Substract Height ["h2", ".divToolbar"]
//and optional numeric value (30)
//"grid" element will dock height to It's parent(windows) size and when it's resized
$(".grid").dockHeightToParent(["h2", ".divToolbar"], 30);
</script>
Image sample: