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.

Syntax for Javascript Location Hash Property

location.hash

or

window.location.hash

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() {
        alert(window.location.hash);
    }

    function setLocationHash() {
        window.location.hash = "#top";
    }
</script>

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.

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.

Recent JavaScript Tutorials

Javascript FSO ShortPath property

Javascript FileSystemObject (FSO) provides a ShortPath property that can be accessed using the folder object or file object returned by the GetFolder or GetFile method.

Javascript FSO Path Property

Javascript FileSystemObject (FSO) provides the Path property that can be accessed through the file object or folder object returned by the GetFile or GelFolder method

Javascript FSO Type property

Javascript FileSystemObject (FSO) provides a Type property that can be accessed through file object or folder object returned by the GetFile or GetFolder method

Javascript FSO ShortName property

Javascript FileSystemObject (FSO) provides a ShortName property that can be accessed using the folder object or file object returned by the GetFolder or GetFile method.

Javascript FSO Name Property

Javascript FileSystemObject (FSO) provides a Name property that can be accessed using file object or folder object.