Create a Link to the Top of a Web Page Without Using Anchors

HtmlAnchor

Html Problem Overview


I have an HTML document that currently has some links to the top of the page using an anchor

<body id="topofpage">
   ...
   <a href="#topofpage">Go to top</a>

However, I don't like needing to create a useless id and how the "#topofpage" shows up in the URL after I click the link. Is there something else I can do to link to the top of the page without using Javascript? I tried removing the anchor completely with <a href=""> but that causes the page to refresh.

Html Solutions


Solution 1 - Html

According to the HTML5 spec the empty fragment # and the special fragment #top will link to the top of the page.

<a href="#">Go to top</a>

<a href="#top">Go to top</a>

There is no need to create a matching anchor if you use these special fragment names.

Solution 2 - Html

You can try using javascript

<a onclick="scroll(0,0)">

Or you can use jQuery

$("#Top").click(function(){
 scroll(0,0);
});

Solution 3 - Html

I know that you said without using JavaScript, but I think that is really the only way to avoid using a real anchor. The following jQuery will replace anchors with the #top href and perform a nice animated scroll to the top without the URL changing (see the original author's page for more info).

$(document).ready(function() {
    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
})

jsfiddle for completeness

However, I would stick with semantic HTML and use anchors for their purpose so that the proper meaning can be interpreted by the maximum number of browsers. Don't forget about people with disabilities that require screen readers or other special browsers. Anchors are guaranteed to work.

In addition to that, Google announced in 2009 some new indexing features that directly take advantage of in-page anchors to provide additional context that the Web searcher might be looking for. In many cases, there might be a section of a page that a user is very interested in. Google can provide a direct link to that anchor of the page for optimum relevance.

Bottom line from my point of view - don't dis the anchors. Use them.

Solution 4 - Html

Solution 5 - Html

<a href="?">top</a> will get you there.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionhugomgView Question on Stackoverflow
Solution 1 - HtmlhugomgView Answer on Stackoverflow
Solution 2 - Htmluser1513192View Answer on Stackoverflow
Solution 3 - HtmlSumoView Answer on Stackoverflow
Solution 4 - HtmlVashView Answer on Stackoverflow
Solution 5 - HtmlBret A. LucasView Answer on Stackoverflow