Retrieving anchor value from URL

Lately i have been trying to get a grasp of the anchor value from the URL using ASP.NET. From what i learned from the forum (This might be wrong since there is a way in PHP( to get the anchor value.)

Case study:

The url above send the user to a page product and then your browser interpret the anchor and scroll down way to the description anchor. But the question is why the heck would i want to get the anchor since it’s just an anchor ? There might be several reasons for that. Here is 2 of them:

  • You might not want to pass an extra parameter in your URL query string because of Referencing issues
  • You would like to perform an action when the page reaches the anchor: Example open an AJAX popup or load some information or Execute a JavaScript in the Description Section of the product.

There might be several other reasons, but these two give you and idea of what is to be achieved.

You can’t get access to the anchor value using server side ASP.NET, it will neither be seen in the Request.Url nor the Request.RawUrl. Therefore those who are trying in vain to get access to this information, don’t bother anymore. You can just use a simple javascript that will do that, and then if you want afterward to either make a new submit to the server or do it in AJAX.

var anchorValue;
var url = document.location;
var strippedUrl = url.toString().split("#");
if(strippedUrl.length > 1)
anchorvalue = strippedUrl[1];

With these few lines of javascript you will be able to determine the value anchor that has been sent in your URL.

6 comments on “Retrieving anchor value from URL

  1. Thanks, really needed it. I thought anchor is passed via tcp/ip along and php would be able to parse it, then again only browser uses it.

  2. jf says:

    Hey, good that it was of help to you, It took me some research and sometime to find a solution to my problem.

  3. Thabo says:

    you can use location.hash to get to this value. you still have to trim the # off the beginning.

  4. jf says:

    Thanks, i’ll update my post and submit your solution on it.

  5. Cyril Pauya says:

    Thanks for this code. The code in the 4th line: “if(strippedUrl.Length > 1)” should have been “if(strippedUrl.length > 1)” but of course if the reader is a programmer he/she already fixed that. 😉

  6. jf says:

    Thanks for pointing this out. I’ve updated the post to correct this. ^_^

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>