window.location.hash returns hash tag in front of value

Ivan Stoyanov picture Ivan Stoyanov · Oct 30, 2012 · Viewed 25k times · Source

I have the following code in MVC3 view:

 $(document).ready(function () {
    if (window.location.hash) {
        var manager= new Manager();

        manager.doSomeStuff(window.location.hash);
    }
});

The interesting thing is that when there is no hash tag in the URL, or there is only a hash tag example:

http://localhost:1223/Index/AboutUs

http://localhost:1223/Index/AboutUs#

When the window.location.hash is empty and the function is not executed. But when there is some value in the hash tag:

http://localhost:1223/Index/AboutUs#categoryId=5&manufacturerId=8

The value in the window.location.hash is #categoryId=5&manufacturerId=8

Can you explain to me why the # tag is included in the value and why when there is no value after the # tag, the window.location.hash is empty.

Answer

Pulkit Mittal picture Pulkit Mittal · Oct 30, 2012

There's nothing much to explain. It is the way it works.

Read more here: http://www.w3schools.com/jsref/prop_loc_hash.asp

Definition and Usage

The hash property returns the anchor portion of a URL, including the hash sign (#).