Go to the top of page functionallity

Here is one of the simplest ways to add scroll to the top feature. Some basic info, example code plus cross-browser issues.

First, let’s create some links:

[code language=”js”]
$(‘h3’).append(‘<a href="#content" class="go-to-the-top"> top of the page</a>’);
[/code]

In this example, we’re adding such link to each h3 (third level header) element, but you can easily customize it to your own needs:

If you can’t (or don’t want to) use typical anchors, you can mimic entire functionality, without them:

[code language=”js”]
$(function()
{
$(‘h3’).append(‘<span class="go-to-the-top"> top of the page</span>’).click(function()
{
$(‘<a name="top-anchor"></a>’).insertBefore($(‘body’).children().eq(0));
window.location.hash = ‘top-anchor’;
});
});
[/code]

Style this link anyway, you’d like. Remember about adding cursor: pointer, if you’re using spans or any other non-anchor elements.

Note, that in second aspect (onclick event on span) you should avoid common solution with $('body').scrollTop(0); as .click code, as it is not working at all in Internet Explorer 9 and older.

The trick with window.location.hash works in IE 9 and the one with <a> tag should work in any browser, that supports Javascript.

Note also, that you can’t use popular ::after and ::before CSS pseudo-element. You can’t insert HTML code (just a pure text) into content property, so you won’t be able to create fully functionall link (first solution). It also doesen’t insert pseudo-elements into DOM, so you can’t bind onclick event to them (second solution).

For obvious reasons, any of these solutions won’t work, if browser has Javascript disabled.

This example is based on this and this StackOverflow answer.

Leave a Reply