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.
The hash property of the Location interface returns a string containing a '#' followed by the fragment identifier of the URL — the ID on the page that the URL is trying to target.
The Location Hash property in HTML is used to return the anchor part of a URL. It can also be used to set the anchor part of the URL. It returns the string which represents the anchor part of a URL including the hash '#' sign.
The location. hash property sets or returns the anchor part of a URL, including the hash sign (#).
Overview. The window. location. hash returns a string that contains a # along with the fragment identifier of the URL. The fragment identifier of the URL starts with a # followed by an identifier that uniquely identifies a section in an HTML document.
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 (#).
You can change it if you want by simply changing the hash name:
//Your old hash name caught in a variable
var nameHash = location.hash;
//Your new hash name without "#"
var newHashName = nameHash.replace("#","");
var hash = window.location.hash.substring(1);
This omits the first character of the string, which is the hash tag.
You can repalce #
but this way will create conflict and won't work with javascript.
Here is window.location reference link.
Here is different usage examples:
$(document).ready(function () {
var urlHash = window.location.hash;
var sampleURL = '#categoryId=5&manufacturerId=8';
if ( urlHash.length > 1 ) {
//do stuff
}else{
//if value is empty, do stuff
}
if ( urlHash === sampleURL ) {
commonResponse();
}
$('a').click(function() {
var target = $(this).attr('href');
if (target === sampleURL ) {
commonResponse();
}
});
function commonResponse() {
//alert('ok');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With