Advanced go to TOP link

This example shows how to create a advanced "Go to Top" link using JavaScript and HTML anchors...
You will notice that this method will not add a #top to the URL.

<!------>
 
<script type="text/javascript">
 
function init(){
    document.getElementById('gtop').onclick = function(){ 
        window.scrollTo(0,0); 
        return false; 
    }
}
 
onload=init;
 
</script>
 
<a name="top"></a>
 
<h1>Top position</h1>
 
<p>
    A long text ....<br/>
    A long text ....<br/>
    A long text ....<br/>
    A long text ....<br/>
    A long text ....<br/>
    A long text ....<br/>
</p>
 
<!-- create a long page -->
<br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/>
 
 
<p>
    Last paragraph.
</p>
 
<br/>
<br/>
 
<a href="#top" id="gtop">Go to top</a>
 
<br/>
<br/>
Snippet Details




Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

Me June 05, 2009 at 21:33
Because this link:
<a href='#TOP'>Back to top</a>

changes the URL and therefore the Back button doesn't go to the expected previous page.
Bill March 24, 2008 at 17:19
Why complicate such a simple task? All you really need to do is add a simple link like this:

<a href='#TOP'>Back to top</a>

No JavaScript or empty anchor tags required.