-1

On the footer of the website I'm working on, I have links to different pages, and in one case, 2 links to the same page with a different hash in the url ,like this :

<a href="http://example.com/mypage#test>Test</a>
<a href="http://example.com/mypage#test2>Test2</a>

These hashes are not true anchors, they reflect some actions the user takes (namely showing/hiding some content). If I come from another page, I navigate without any problem. However, if I am already on "mypage", then the hash changes, but nothing happens. The browser detects and anchor change and thus tries to navigate to the anchor.
That's fair enough, but I want my user to be actually redirected to "http://example.com/mypage#test2", as if he copy-pasted it himself in the address bar. How can I achieve that ?

I could use the hashchange event but it would make it complicated to manage the rest of the javascript, so I wonder if there is a simpler way to do it.

Ogier
  • 150
  • 9

2 Answers2

0

You have a very simple solution if you are using jQuery:

$(window).on('hashchange', function() {
    //code
});

Check out this: On - window.location.hash - Change?

Also this MDN documentation.

Luka Čelebić
  • 1,083
  • 11
  • 21
0

Use the location.hash property of the window object to find out what the anchor is. To detect a change in the hash, with plain javascript, just use the onhashchange event.

window.onhashchange = new function() {
    window.location.replace("http://example.com/mypage" + window.location.hash);
});
Gilles Lesire
  • 1,237
  • 17
  • 33