>

How to use JQUERY to set a DIV height to stretch the DIV to the Bottom of the Screen.

Posted on January 9, 2012 By

Many times it is necessary to have a div positioned as it normally would, but have the height set to extend to the bottom of the browser window.  Setting the height to 100% does not work, it will either stretch the div to the entire size of the document (not the visible window), or have no effect.

I have solved this problem with a simple JQuery script.  Here is the JQuery function that will resize the DIV.  I will explain how it works below the code:

function setDIVHeight() {
            var theDiv = $('div#container');
            var divTop = theDiv.offset().top;
            var winHeight = $(window).height();
            var divHeight = winHeight - divTop;
            theDiv.height(divHeight);

        }

 

Line 1 gets a reference to the div object (assuming an ID of container).
Line 2 finds the top of the div; where it starts in the normal page flow.
Line 3 finds the height of the visible browser window.  We want to extend the div to this spot.
Line 4 calculates the div height, by subtracting the top of the div (line 2) from the window height (line 3).
Line 5 sets the div height calculated in line 4.

The next step is to execute this function when the page loads or the browser resizes.  We do this with the .ready and .resize event handlers.  Here is the full code to do this.

<script  type="text/javascript">
   $(document).ready(function () {
            setDIVHeight();
        });

   $(window).resize(function () {
            setDIVHeight();
   });

&amp;amp;nbsp;

   function setDIVHeight() {
            var theDiv = $('div#container');
            var divTop = theDiv.offset().top;
            var winHeight = $(window).height();
            var divHeight = winHeight - divTop;
            theDiv.height(divHeight);

        }
   

</script>

 

Scripting     , , , ,