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 Comments
This might come in handy ,but I like the traditinal ones more :) (exp. a href="#content” )
Comment (#) by Marko Mihelcic — 23rd May 2006.
Nice one, Maratz! Another one of your little extra thingies that makes site more “user-friendly".
Comment (#) by Alen — 25th May 2006.
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.
Comment (#) by BIZZY — 25th May 2006.
@bizzy: if a user has JS turned off, she will see the link nevertheless.
Comment (#) by marko — 25th May 2006.
though i try not to use javascript if its avoidable …its a nifty code snippet, thanks for sharing.
Comment (#) by nivid — 26th May 2006.
add a event listener? window resized?
Comment (#) by Johan — 28th May 2006.
very handy - thank you very much for sharing!
Comment (#) by matthias — 4th June 2006.
Sorry, the comment form is closed at this time, but if you have anything to say, please send me a message.