-1

I'm almost done with my previous issue, but now I'm dealing with something more subtle and annoying.

I've got a page with some links like these ones:

<a href = "page.html#1">First content</a>
<a href = "page.html#2">Second content</a>

In the page page.html there is some javascript, something like this:

document.write (window.location.href);

So, I click on the first link, and I see (in a different frame) the page "page.html", correctly starting at anchor #1. At the end the javascript writes "page.html#1", and this is correct. Then I click on the second link, and I see the page "page.html" changing its starting point, now correctly set at anchor #2. But at the end of the page I still see "page.html#1", not "page.html#2" as I expected. I think this happens because the page is exactly the same as before, only the starting point changed, so the "location.href" was not changed, despite a difference in the hash.

Is there a way to solve the problem, and get the original location.href, the one with the correct hash?

8
  • 1
    The problem is that the page is not actually changing. You will need to execute the document.write() functionality again instead of relying on the page reload to execute it for you. Commented May 25, 2021 at 15:27
  • 1
    Tangential, but document.write() has been somewhat obsolete for some time now - you should probably leverage more proper DOM manipulation methods. Further reading Commented May 25, 2021 at 15:28
  • Document.write was just a way to find what the problem was. What I need is to identify the correct hash, as in the original link. Commented May 25, 2021 at 15:37
  • @AndreaCarta window.location.href does identify the correct hash. It's just that your code is not executed again when navigating inside the page. Commented May 26, 2021 at 0:14
  • 1
    @Bergi: I stand corrected. Against my expectations the hashchange event handler did indeed work, and the code (after having been moved inside the handler) now works correctly). Yours was a very good suggestion. Commented May 27, 2021 at 20:57

1 Answer 1

0

use onclick event attribute:

<a href="page.html#1" onclick="document.write(window.location.href);">First content</a>
<a href = "page.html#2" onclick="document.write(window.location.href);">Second content</a>
Sign up to request clarification or add additional context in comments.

1 Comment

this only prints the location.href of the page with the link, inside the page with the link. I need the location.href of the page linked, from inside the page linked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.