Search code examples
javascriptonloadfragment-identifier

loading the same page with a different Fragment ID does not cause page to reload?


Basically, I have a number of links on the page - index.html, they look something like this:

  <li><a href="index.html#0">test 0</a></li>
  <li><a href="index.html#1">test 1</a></li>
  <li><a href="index.html#2">test 2</a></li>
  <li><a href="index.html#3">test 3</a></li>

I attached a function in window.onload event that will open up an alert box containing the fragment ID, so if I click on the first link, I should get an alert box with "0", etc.

However, I only get an alert box when I access index.html from the URL bar and press enter. When I click on the links, no alert box showed up. I think it's because the window.onload event doesn't get called... Does anyone know how to solve this problem?


Solution

  • You need window.onhashchange event, which gets triggered on anchor navigation https://developer.mozilla.org/en/DOM/window.onhashchange For unsupporting UAs you have to process onclick event on document.links and figure out if the link points to currect document (ie: only link.hash differs from location.href)