51

I learned "window.location.hash" new and tried in my jquery code instead of "window.location.href" and both of them gave same results.

Code is here :

window.location.href = ($(e.currentTarget).attr("href"));
window.location.hash = ($(e.currentTarget).attr("href"));

What is the difference between them?

kalaba2003
  • 1,171
  • 2
  • 19
  • 31
  • 1
    http://www.w3schools.com/jsref/obj_location.asp – Evan Mulawski May 21 '12 at 15:48
  • The value of this property could be different in different browsers. A safe way to get the hash property would be to instead use: `var hash = (location.href.split("#")[1] || "");` – naXa Jul 10 '17 at 08:42
  • http://lea.verou.me/2011/05/get-your-hash-the-bulletproof-way/ `var hash = location.hash.substring(1);` – lowtechsun Mar 21 '20 at 14:20

6 Answers6

73

For an URL like http://[www.example.com]:80/search?q=devmo#test

hash return the part of the URL that follows the # symbol, including the # symbol. You can listen for the hashchange event to get notified of changes to the hash in supporting browsers.

Returns: #test

href returns the entire URL.

Returns: http://[www.example.com]:80/search?q=devmo#test

Read More

Tadeck
  • 117,059
  • 25
  • 140
  • 191
Selvakumar Arumugam
  • 76,636
  • 14
  • 118
  • 132
11

Test it on for example http://stackoverflow.com/#Page

href = http://stackoverflow.com/#Page
hash = #Page
Tadeck
  • 117,059
  • 25
  • 140
  • 191
Henrik Karlsson
  • 5,127
  • 4
  • 22
  • 40
4

href is the url

hash is only the anchor after the url

http://www.xxxxxxx.com#anchor

http://www.xxxxxxx.com#anchor is the href

"#anchor" is the hash

Jerome Cance
  • 7,769
  • 11
  • 49
  • 103
3

hash and href are both properties of the window.location object. hash is the part of the URL from the # on (or an empty string if there is no #), while href is a string representation of the whole URL.

lonesomeday
  • 215,182
  • 48
  • 300
  • 305
2

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

DisplayName
  • 3,065
  • 5
  • 36
  • 40
2

Here is the simple example for difference between window.location.href and window.location.hash

For the URL http://www.manm.com/member/#!create:

  • href: http://www.manam.com/member/#!create
  • hash: #!create
Tunaki
  • 116,530
  • 39
  • 281
  • 370