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>
$(".grid").dockHeightToParent(["h2", ".divToolbar"], 30);
</script>
Image sample: