JavaScript Stuff: CSS Dynamic Height and Width Using jQuery

While working away on Haven, our online development app, I found the need to be able to dynamically set the height and width of a few elements on the projects main editor page. It’s the part of the application that will look less like a web page and more like an application. I’m still rather new to JavaScript and extremely new to jQuery so figuring out how to do this was a little time consuming. The end result was so freaking awesome and flexible that I thought I’d share it with the world.

To use this code just add the class dynamic-height or dynamic-width to the elements you want to have fill the screen. Then add the class height-offset or width-offset to any elements that have a static height or width that should be taken into account when calculating the white space left on the screen. Then add setDynamicDimensions() as the onresize event and as a script block at the bottom of the page. Just like that you will have elements that fill your page without causing scrollbars and the users screen size or resolution won’t matter.

/*
* Finds all elements that have a class of dynamic-height or dynamic-width and sets their
* heights and widths appropriately offset by the heights or widths of all elements that
* have a class of height-offset or width-offset.
*/
function setDynamicDimensions()
{
var heightOffset = 0;
var widthOffset = 0;

// Calculate the height offset
$(".height-offset").each(function(){
heightOffset += $(this).outerHeight();
});

// Calculate the width offset
$(".width-offset").each(function(){
widthOffset += $(this).outerWidth();
});

$(".dynamic-height").each(function(){
// Take into account this objects margin, border and padding
var myOffset = 0;
myOffset += parseInt($(this).css('padding-top'));
myOffset += parseInt($(this).css('padding-bottom'));
myOffset += parseInt($(this).css('margin-top'));
myOffset += parseInt($(this).css('margin-bottom'));
myOffset += parseInt($(this).css('border-top-width'));
myOffset += parseInt($(this).css('border-bottom-width'));

$(this).css("height", $(window).height() - heightOffset - myOffset + "px");
});

$(".dynamic-width").each(function(){
// Take into account this objects margin, border and padding
var myOffset = 0;
myOffset += parseInt($(this).css('padding-left'));
myOffset += parseInt($(this).css('padding-right'));
myOffset += parseInt($(this).css('margin-left'));
myOffset += parseInt($(this).css('margin-right'));
myOffset += parseInt($(this).css('border-left-width'));
myOffset += parseInt($(this).css('border-right-width'));

$(this).css("width", $(window).width() - widthOffset - myOffset + "px");
});
}

2 Comments

  1. demo?

  2. Good idea, perhaps I can throw one together.

Submit a Comment

Your email address will not be published. Required fields are marked *