Wednesday, February 15, 2012

Re-sizing elements with jQuery

For the past couple of months on and off I have been looking for a script to re-size a div dynamically based on the browser size of the user. I don't need anything that dynamically re-sizes as the user changes the size of the window but just on page load.

Like many I spent a lot of time searching and testing but couldn't find anything that actually worked so today (after trying another 6 "solutions") I decided to write a script myself.

The web application I'm developing already uses jQuery so I thought I would start there. I Google'd a number of terms including "jQuery resize HTML element" and "jQuery change HTML element" without luck, then I tried the obvious "jQuery change element height" and found the solution in the first link with the jQuery .height() function.

I took some inspiration from a couple of pure JavaScript solutions that I found and wrote the following


The code is actually really simple, we start with the jQuery property that prepares our environment for our function.

Next we create a variable that calculates the height of the window and deducts the height of the other elements on the page dynamically, this looks like this


Finally we re-size our remaining element with


As you may have realized it's a very standard layout with a header, content area and footer that I'm working with, however I did test it on a number of other elements and found the only thing you need to know is what elements are going to be on the page.

Put this into the head of your page and you're away.

There is something that you need to know before starting with this script, apart from the obvious jQuery pre-requisite. This is that it does not re-size the elements as you change the window size but only on page load or "document ready".

Finally, I also recommend you specify a minimum height of the element in your CSS with something like this


I hope that you find this helpful... happy coding!

No comments:

Post a Comment