main content, site navigation, search

Smart ‘back to top’ link

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 shouts to “Smart ‘back to top’ link”

  1. Marko Mihelcic
    001—2006.05.23.17:25

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

  2. Alen
    002—2006.05.25.17:37

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

  3. BIZZY
    003—2006.05.25.18:53

    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. marko
    004—2006.05.25.21:40

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

  5. nivid
    005—2006.05.26.17:59

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

  6. Johan
    006—2006.05.28.16:12

    add a event listener? window resized?

  7. matthias
    007—2006.06.04.18:02

    very handy – thank you very much for sharing!

Comments are closed.

main content, site navigation, search