Gabriel Spiteri
Gabriel Spiteri

Reputation: 4978

html anchor works only once

I am ashamed to say that I have an anchor issue.

So I have this code:

<a name="map"></a>

$("div.store_list").click(function() {          
    //do some stuff         
    location.href = location.href + '#map'
});

When doing the first click it works fine. And the URL changes to:

http://mydomain.local/stores#map

Second click the URL changes to the following and it doesn't work:

http://mydomain.local/stores#map#map

Any suggestions? Thanks

Upvotes: 4

Views: 5665

Answers (6)

Dean Sharon
Dean Sharon

Reputation: 11

Reseting the scroll position on anchor link click event worked for me. Seems like theres at least one bug with anchor links in Chrome versions 76 - 86 (The most recent macOS version at time of this posting).

Try:

window.scrollTo(0, 0)

Upvotes: 1

Luke
Luke

Reputation: 23680

The accepted solution didn't work for me sadly. I managed to get it to work in Chrome by setting the anchor value to "#" first, then setting it to my desired location.

document.location.href = "#";
document.location.href = "#myAnchor";

Once I did this, it fired every time I click a link with an anchor tag in it.

$(document).on('click', '.jump_to_instance', e => {

    // Get anchor name
    var anchorName = $(e.target).attr("href");

    // Set anchor to nothing first
    document.location.href = "#";

    // Set to new anchor value
    document.location.href = anchorName;
});

<a href="#myAnchor">Click me to go to anchor, I should work multiple times</a>

<div id="myAnchor">Will jump to here</div>

Upvotes: 0

nipo
nipo

Reputation: 180

In case you scroll and need to jump again, this has worked for me:

onclick="location.hash=''; location.hash='#map';"

Upvotes: 4

Gabriel Spiteri
Gabriel Spiteri

Reputation: 4978

Issue was solved using: document.location = "#map";

Upvotes: 2

Kon
Kon

Reputation: 27441

You can check to make sure the URL doesn't already contain the value you're appending:

$("div.store_list").click(function() {          
    //do some stuff
    if (location.href.indexOf('#map') == -1) {         
        location.href += '#map';
    }
});

Upvotes: 0

Paul Dixon
Paul Dixon

Reputation: 300855

Try location.hash instead, e.g.

location.hash='#map'

Upvotes: 2

Related Questions