If you are reading this, please get modern browser.
skip to main content | skip to main navigation | skip to secondary content

Smart ‘back to top’ link

~ 22nd May 2006. · 13:55 CET · permanent link · printer friendly ~

Back to top link’s purpose is to quickly position the viewport back to a beginning of a web page. Sometimes you have a variable height of the content and this link is unnecessary if a particular page is shorter than viewport height. With this simple JavaScript, you can hide it depending on page’s height. See the example web site.

var d = document;
onload = function() {
    var viewport_height = (self.innerHeight) ? self.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : (document.body) ? document.body.clientHeight : 0;
    var page_height = d.getElementsByTagName('body')[0].offsetHeight;
    var ttl = d.getElementById('to_top_link');
    if (page_height < viewport_height) ttl.style.visibility = 'hidden';
};

7 Comments

  1. This might come in handy ,but I like the traditinal ones more :) (exp. a href="#content” )

  2. Nice one, Maratz! Another one of your little extra thingies that makes site more “user-friendly".

  3. In my opinion it’s step back because it makes site less usable for users with careful firewall or javascripts turned off. Bad solution contrary traditional solution.

  4. @bizzy: if a user has JS turned off, she will see the link nevertheless.

  5. though i try not to use javascript if its avoidable …its a nifty code snippet, thanks for sharing.

  6. add a event listener? window resized?

  7. very handy - thank you very much for sharing!

Sorry, the comment form is closed at this time, but if you have anything to say, please send me a message.

* Please keep in mind that this is a personal web site and it does not reflect the position or opinion of my respective employers, organizations or partners.

Typetester – compare screen type Supported by Veer.

What is this?

A web log of Marko Dugonjić, web professional from Croatia. Topics covered:

Translate this site

German, Spanish, Italian, French or Japanese (via).

See you there!

Feel like buying a book?

Try with maratz.com aStore

Worth visiting

top of the page | skip to main content | skip to main navigation | skip to secondary content