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) = 'hidden';

Marko Dugonjić is a designer specialized in user experience design, web typography and web standards. He runs a nanoscale user interface studio Creative Nights and organizes FFWD.PRO, a micro-conference and workshops for web professionals.

Interested in more content like this?