Auto-Hiding “Back to Top” Link with jQuery

A common usability feature on a lot of sites is a “Back to top” link at the bottom of long pages, allowing users to quickly get back to the start of the document without scrolling.

These are often built into the CMS or template itself rather than the content, so it’s entirely possible for them to appear on pages too short to be useful.

Here’s a jQuery function I wrote to remove the “Back to top” link if the page’s content isn’t longer than the window.

[js]jQuery.fn.autohidebacktotop = function() {
if ($(“html, body”).height() <= $(window).height()) { $("#autohidebacktotop").remove(); } this.bind("click", function() { $("html, body").animate({scrollTop:0}); return false; }); }; [/js] The accompanying HTML: [html]

Back to top

[/html]

And then you can call it like so:

[js]$(document).ready(function(){
$(“#autohidebacktotop”).autohidebacktotop();
});[/js]

How is this better?

  • Gracefully degrading, still works if JavaScript isn’t enabled
  • #autohidebacktotop can be styled with CSS as normal
  • Nifty scrolling animation