I thought I'd show off a super-duper little function that I now slip into practically every site I build without really thinking about it.
A bunch of our more recent sites feature footers that truly book-end the site; that scream: "This is the end! You can tell, because there are shards of broken wood or torn fabric that suggest this page has reached its contentual termination! All change here!". The problem is, of course, that a) you might have a really short page of content (like "Thanks for filling out that form!"); and 3) there's just no accounting for screen size. Consequently your beautiful end-piece might end up floating in the middle of the screen like a sad clown that unsuccessfully tried to hang himself.
So, with that disturbing simile in mind, here's some handy jQuery to ensure your footer will always stick to the bottom of your page:
  <!--
 Â
  $(document).ready(function() {
  Â
   var docHeight = $(window).height();
   var footerHeight = $('#footer').height();
   var footerTop = $('#footer').position().top + footerHeight;
  Â
   if (footerTop < docHeight) {
    $('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
   }
  });
 Â
  // -->
 </script>
Once the DOM is ready, this code checks the height of the browser viewport ($(window).height()), the height of the footer element, and the 'top' position of the footer element (technically it's actually the bottom of the footer, since it's the footer's top position plus its height).
Then, if footerTop is less than docHeight, the footer's margin-top CSS property is set to push it to the bottom of the page, plus an extra 10px for good measure.
A couple of assumptions are made for this code to work right out of the box:
- Your footer has the ID #footer;
- Your footer is an explicit height, or;
- It contains elements with explicit heights that might not be fully loaded on $document(ready) - like images
And shazam! You're done.



Pingback: jQuery: Stick your div to the bottom of a short page, v2.0 « Gaijin Designâ„¢ //_ Technoblogicalog