Sticky footer with jQuery


A sticky footer solution that allows a variable-height footer to be 'stuck' to the bottom of the page when the content isn't quite long enough. It does this by calculating the gap between the bottom of the footer and the window, then adds that value to the footer's top margin (to push it down). This happens whenever the window is resized (to allow for changing orientation on mobile devices, etc.).

This method doesn't require any specific HTML, CSS, classes, table layouts, etc. - use it on your existing site without changing a thing. It does use jQuery, but then what modern website doesn't? This also means it'll revert to a normal, non-sticky footer if javascript is disabled or not available (progressive enhancement).

To use, add this code to a .js file in your theme, surround it with the appropriate closures, behaviours, etc. and make sure it's included on every page. Then just change the 'footer' variable to reference the element you want to be made sticky and you're done!

Get raw version
  1. // Footer element to be made sticky
  2. var footer = '#footer';
  4. // Get footer's top margin
  5. var footerMargin = parseInt($(footer).css('margin-top'));
  7. $(window).resize(function () {
  8. // Reset margin
  9. $(footer).css('margin-top', footerMargin + 'px');
  11. // Get window height
  12. var windowHeight = $(window).height();
  14. // Get bottom of footer
  15. var footerTop = $(footer).offset().top;
  16. var footerHeight = $(footer).outerHeight(true); // Includes any margins
  17. var footerBottom = footerTop + footerHeight;
  19. if (windowHeight > footerBottom) {
  20. // Get difference between window height and bottom of footer
  21. var difference = windowHeight - footerBottom;
  23. // Add difference to footer's top margin
  24. var newMargin = footerMargin + difference;
  25. $(footer).css('margin-top', newMargin + 'px');
  26. }
  27. });