136

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.

I have two problems regarding anchors.

The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.

So the structure of the anchors is:

<ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
</ul>

<div class="wrap">
    <a name="one">text 1</a>
    <a name="two">text 2</a>
    <a name="three" class="box">text 3</a>
</div>

Okay, if you will click one of the links the url will automatically change to

www.domain.com/page#1

At the end this should be just:

www.domain.com/page

So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.

I have found this function:

function jumpto(anchor){
    window.location.href = "#"+anchor;
}

and calling that function with:

<a onclick="jumpto('one');">One</a>

what will be the same like before. It will add the hash to the url. I also added

<a onclick="jumpto('one'); return false;">

without success. So if there is someone who could tell me how to solve this I really would appreciate.

Thanks a lot.

Mickaël Leger
  • 3,345
  • 1
  • 13
  • 32
bonny
  • 2,937
  • 11
  • 34
  • 56
  • Not sure about this, but you could try manually writing to the hash property after the jump. For example set a timeout in the onclick handler which sets `window.location.hash=''`. – Jeff Dec 06 '12 at 02:21
  • Do you mean you don't want to have the # shown in the URL when jumping to another section in the same webpage? – Roger Ng Dec 06 '12 at 02:24
  • 2
    In that case you will either have to manipulate the scrollTop of the window, typically by `window.scrollTo` or the corresponding jQuery helper: http://stackoverflow.com/questions/6677035/jquery-scroll-to-element or http://stackoverflow.com/questions/500336/how-to-scroll-to-an-element-in-jquery – Frank van Puffelen Dec 06 '12 at 02:34
  • @Jeff - If you do `location.hash=''`, the `#` remains there. – Derek 朕會功夫 Dec 06 '12 at 02:58
  • 1
    Do not do that, please. Hashes are good when saving the page in your bookmarks. – Marco Sulla Jan 12 '15 at 17:59
  • Perhaps worth noting that the name attribute of anchor tags is deprecated. You should use id instead. – Dylan Smith Oct 25 '19 at 17:57

5 Answers5

217

You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.

Here is a lazier way to do that:

function jump(h){
    var url = location.href;               //Save down the URL without hash.
    location.href = "#"+h;                 //Go to the target element.
    history.replaceState(null,null,url);   //Don't like hashes. Changing it back.
}

This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:

function jump(h){
    var top = document.getElementById(h).offsetTop; //Getting Y of target element
    window.scrollTo(0, top);                        //Go there directly or some transition
}​

Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/

You can also use .scrollIntoView:

document.getElementById(h).scrollIntoView();   //Even IE6 supports this

(Well I lied. It's not complicated at all.)

brasofilo
  • 23,940
  • 15
  • 86
  • 168
Derek 朕會功夫
  • 84,678
  • 41
  • 166
  • 228
14

I think it is much more simple solution:

window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"

This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.

suayip uzulmez
  • 384
  • 4
  • 19
Adam111p
  • 2,529
  • 1
  • 20
  • 18
3

Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }
Yuri
  • 3,283
  • 1
  • 19
  • 37
cmc
  • 572
  • 4
  • 15
2

Because when you do

window.location.href = "#"+anchor;

You load a new page, you can do:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>
2

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.

On the .html file I have:

<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>

On the .js file I have

function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.

I use Google Chrome.

Note: This idea comes from linking on the same page using

<a href="#test100">Test link</a>

which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.

Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ☺

S.Doe_Dude
  • 25
  • 1
  • 3