Seipas
Seipas

Reputation: 123

Get URL/anchor inside an onclick function binded to an anchor link AFTER following this link

Context

CSS lack a "a:current" selector or access to the current URL, so I am trying to code vanilla JS to color the links in my menu which link to the same page/anchor.

I run a function each time I click on an anchor link to check for each menu link if it corresponds to the new anchor. Problem : document.URL refers to the URL BEFORE clicking the link. Please note that I think I can color my links in a different way, but this is not part of the question (you can comment if you have advices).

Code to reproduce

<!DOCTYPE html>
<html>
  <head>
    <meta http-equiv='Content-Type' content='text/html;charset=utf-8' />
  </head>
  <body>
    <script>
      var check_anchor = function()
      {
        document.getElementById('url_log').innerHTML = document.URL;
      }
    </script>
    <a href='#anchor_1' onclick='check_anchor();'>Anchor 1</a>
    <a href='#anchor_2' onclick='check_anchor();'>Anchor 2</a>
    <a href='#anchor_3' onclick='check_anchor();'>Anchor 3</a>
    <p>URL is <span id='url_log'></span></p>
  </body>
</html>

Example :

When you click anchor 2 : "file:///home/[...]/Anchor_Example.html"

When you click anchor 3 : "file:///home/[...]/Anchor_Example.html#anchor_2"

When you click anchor 1 : "file:///home/[...]/Anchor_Example.html#anchor_3"

When you click anchor 1 : "file:///home/[...]/Anchor_Example.html#anchor_1"

(in that order : there is "a delay" : the URL printed is the URL before clicking the link. What I want is when you click anchor 1 : "file:///home/[...]/Anchor_Example.html#anchor_1")

Question

Is it easily possible to get the URL after following an anchor link, or call the onClick event after following the link ? If so, how would you do it ?

Sorry if this question seems dumb or have already been answered (I looked for it without success).

Upvotes: 2

Views: 900

Answers (1)

Deryck
Deryck

Reputation: 7668

This is where window.onhashchange comes in handy.

Check it out on MDN

Not a dumb question at all.

Anytime inside that event handler you feel you want to know what the new URL is, you can use location.href or to get just the changed part (the hash) use location.hash

window.onhashchange = function () {
    console.log(location.hash);  // new hash/anchor location
}

Upvotes: 2

Related Questions