“Top” Watermark Using MooTools

Whenever you have a long page worth of content, you generally want to add a "top" anchor link at the bottom of the page so that your user doesn't have to scroll forever to get to the top. The only problem with this method is that I may want to get to the top of the page from somewhere in the middle. Using MooTools, we can create a "top" link as a watermark that follows the users down the page.

The XHTML

<a href="#top" id="gototop" class="no-click no-print">Top of Page</a>

Place this anywhere inside the page that you would like.

The CSS

#gototop { display:none; position:fixed; right:5px; bottom:5px; }

This code positions the element in a fixed position so it always stays in the same spot.

The MooTools JavaScript

/* smoothscroll - scroll smoothly to the top*/ new SmoothScroll({duration:500}); /* go to top after 300 pixels down */ var gototop = $('gototop'); gototop.set('opacity','0').setStyle('display','block'); window.addEvent('scroll',function(e) { gototop.fade((window.getScroll().y > 300) ? 'in' : 'out') });

The code is surprisingly short. Of course we use SmoothScroll to make the transition smoothe. You may adjust the pixel trigger amount however you'd like. Unfortunately the above code doesn't work in IE6.

The IE Fix

/* go to top */ var gototop = $('gototop'); gototop.set('opacity','0').setStyle('display','block'); window.addEvent('scroll',function(e) { if(Browser.Engine.trident4) { gototop.setStyles({ 'position': 'absolute', 'bottom': window.getPosition().y + 10, 'width': 100 }); } gototop.fade((window.getScroll().y > 300) ? 'in' : 'out') });

I like this method so much that I use it on my website.

Shouldn't this be a plugin?

Don't worry -- ScrollSpy is coming soon enough. :)