What is the difference between "window.location.href" and "window.location.hash"?
Asked Answered
V

6

54

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?

Vasoinhibitor answered 21/5, 2012 at 15:46 Comment(3)
w3schools.com/jsref/obj_location.aspEugenie
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] || "");Unswear
lea.verou.me/2011/05/get-your-hash-the-bulletproof-way var hash = location.hash.substring(1);Diopside
L
79

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

  • hash - returns 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

Leastwise answered 21/5, 2012 at 15:49 Comment(0)
U
11

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

href = http://stackoverflow.com/#Page
hash = #Page
Ullage answered 21/5, 2012 at 15:49 Comment(0)
F
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

Fronniah answered 21/5, 2012 at 15:47 Comment(0)
U
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.

Ulmaceous answered 21/5, 2012 at 15:48 Comment(1)
Pretty sure it includes the # character.Snore
M
3

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

Metametabel answered 21/5, 2012 at 15:48 Comment(0)
M
3

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
Micro answered 18/6, 2016 at 10:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.