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

820 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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)

0
On

Changing the fragment is intended to move from section to section within a specific page. When you click one of your links it just changes the fragment, the page itself is left untouched. Since the page doesn't change, there is no page load event and thus the onload handler is not called.

You need an onhashchange handler instead of an onload handler. Beware though that not all browsers support onhashchange so you'll have to muck about with a hand rolled version for some browsers. If you're doing a lot of this sort of thing then you might want to look at Sammy or a similar library to take care of the details for you.