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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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.

Answers:

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.

Questions:
Answers:

You can try using javascript

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

Or you can use jQuery

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

Questions:
Answers:

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.

Questions:
Answers:

Another useful way of using the anchor tag to get the top of the page is

<a href='#top'> Go back to the top of the page.</a>

using it like this makes your page automatically scroll to the top of the current page. Hope this is useful to someone.

Questions:
Answers:

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