The Location hash property returns/appends a string value (anchor part) to a URL. Anchor part is prefixed with ‘#’ automatically and then appended.
Syntax
Following is the syntax −
- Returning value of the hash property
location.hash
- Value of the hash property set
location.hash = ‘string’
Example
Let us see an example for Location hash property −
<!DOCTYPE html> <html> <head> <title>Location hash</title> <style> form { width:70%; margin: 0 auto; text-align: center; } * { padding: 2px; margin:5px; } input[type="button"] { border-radius: 10px; } </style> </head> <body> <form> <fieldset> <legend>Location-hash</legend> <label for="urlSelect">Current URL:</label> <input type="url" size="27" id="urlSelect" value="https://www.example.com/"> <input type="text" id="textSelect" placeholder="hash value..."> <input type="button" onclick="setHashValue()" value="Go To URL"> <div id="divDisplay"></div> </fieldset> </form> <script> var divDisplay = document.getElementById("divDisplay"); var urlSelect = document.getElementById("urlSelect"); var textSelect = document.getElementById("textSelect"); function setHashValue() { if(textSelect.value !== ''){ location.hash = textSelect.value; urlSelect.value += location.hash; divDisplay.textContent = 'Page loaded. Current URL active'; } else { divDisplay.textContent = 'Please provide a hash value'; } } </script> </body> </html>
Output
This will produce the following output −
Before clicking ‘Go To Url’ button −
After clicking ‘Go To Url’ button with hash value set −