Vertical Responsiveness (using jQuery)

Just a quick post on a simple way to make an element vertically responsive using jQuery. I originally used this for a sidebar which was position:fixed; and so I needed to ensure the height was correct to fit perfectly between an fixed header and footer.

Implementation is fairly simple and includes just 3 sections of code.

  1. Create a function to check the height of the window, then calculate and set the height of the vertically responsive element.
    function setSidebarHeight() {
        /*Get the height of the window*/
        var windowHeight = $(window).height();
        /*Calculate the height that the sidebar should be*/
        var sidebarHeight = windowHeight - 145;
        /*Set the height of the sidebar*/
        $('#sidebar').css("height", sidebarHeight);
  2. Call the function on document ready so that the height of the sidebar is set to the correct height when the site loads.
    $(document).ready(function () {
  3. The height should also be set whenever the window size is changed. I found, in my case, to improve performance it was better to also use a timeout to prevent the function being called too often. This works by setting the function to be called after 1 second, but then cancelling the timeout if the window changes size again. This would then help ensure the size only changes when the window has reached its new size.
    var timerForWindowResize;
    $(window).resize(function () {
        timerForWindowResize = setTimeout("setSidebarHeight();", 1000);

And that's the basic idea. Hope that helps someone out.