Tutorial jQuery Sticky Footer

by in , 0

In general the CSS Sticky Footer is the best way to go, as it works perfectly smoothly and doesn't require JavaScript. If the markup required simply isn't possible, this jQuery JavaScript might be an option.

HTML

Just make sure the #footer is the last visible thing on your page.

<div id="footer">
    Sticky Footer
</div>

CSS

Giving it a set height is the most fool-proof.

#footer { height: 100px; }

jQuery

When the window loads, and when it is scrolled or resized, it is tested whether the pages content is shorter than the window's height. If it is, that means there is white space underneath the content before the end of the window, so the footer should be repositioned to the bottom of the window. If not, the footer can retain it's normal static positioning.

// Window load event used just in case window height is dependant upon images
$(window).bind("load", function() { 
       
       var footerHeight = 0,
           footerTop = 0,
           $footer = $("#footer");
           
       positionFooter();
       
       function positionFooter() {
       
                footerHeight = $footer.height();
                footerTop = ($(window).scrollTop()+$(window).height()-footerHeight)+"px";
       
               if ( ($(document.body).height()+footerHeight) < $(window).height()) {
                   $footer.css({
                        position: "absolute"
                   }).animate({
                        top: footerTop
                   })
               } else {
                   $footer.css({
                        position: "static"
                   })
               }
               
       }

       $(window)
               .scroll(positionFooter)
               .resize(positionFooter)
               
});

Demo

View Demo

Leave a Reply