Javascript Location Hash with Example

Updated on 22 Mar 2012,
Published on 10 Jul 2008

Javascript location hash property sets or returns the value from the hash sign "#" in the current URL of the browser window. Javascript location hash actually returns the bookmark name form the current URL. Bookmark hash "#" sign provides the functionality to target the named anchor HTML <a> tag within the same other web pages. When you click on any link text that targets the bookmarked location of any webpage it adds the "#" symbol and bookmark name to the end of the URL. You can place the location.hash or window.location.hash code inside the target page to retrieve the current bookmark name from the URL. You can call the function at page load or click event of the button.

JavaScript Window Location Object Examples:

You can see the live samples and examples of JavaScript Window Location Object from the following links:

Syntax for Javascript Location Hash Property




Both above code syntax returns the same value from hash "#" sign in the current URL.

To set the bookmark hash value using location hash property you can use the following syntax:

location.hash = "#Value";

Use "#" hash sign with value to target the named anchor tag.

location.hash = "#bottom";

Example of Javascript Location Hash Property

<script type="text/javascript" language="javascript">
    function getLocationHash() {

    function setLocationHash() {
        window.location.hash = "#top";

Above example shows the use of location.hash property. First anchor <a> tag targets the anchor tag with name="bottom" that adds the "#bottom" to the end of the current URL. Similarly second link targets the anchor tag with name="top" that adds the "#top" to the end of the current URL. You can get the location.hash result as "#top" or "#bottom" according to the value added at the end of current URL. setLocationHash function will change the value from "#" hash sign in the current URL.


You can see the output of above discussed code from the following link:

JavaScript window.location.hash

Continue to next tutorial: Javascript Location Host with Example to learn how to get the domain name and port number of current URL using JavaScript.

5 Responses to "Javascript Location Hash with Example"
Do you have a basic example on how the location.hash() work?
Might help to read this in case you need to set hash and get into troubble like i did ;- )
Thanks. I appreciate this tip.
Very useful for all cross browser. Thank you
wow this is very useful on my site inorder to build animation effects thanks
Leave a Comment
* required
* required
* will not be published
* optional
* hint:
  • Subscribe via Email