Managing the URL Hash with Javascript

Use-Cases of this tutorial

  • Know how to get hash fragment of a specific URL, or of the current URL.
  • Know how to change hash fragment of a specific URL, or of the current URL.
  • Know how to detect a change in hash value in the current URL.

The Javascript URL object can be used to get and set hash value of a given url. To detect a change in hash in the current url, the hashchange event can be listened to.

Getting the URL Hash

The hash of a url can be found by creating a new URL Javascript object from the URL string, and then using its hash property to get the value of the hash fragment. Note that this will include the # character also.

If the url does not contains a hash, then an empty string "" will be returned.

  • Get hash of a given url

    var some_url = 'https://usefulangle.com/posts?123#slider'
    
    var hash = new URL(some_url).hash;
    
    // "#slider"
    console.log(hash);
    
  • Get hash of the current url

    // document.URL refers to the current url
    var hash = new URL(document.URL).hash;
    
    console.log(hash);
    

Changing the URL Hash

  • Change hash of a given url

    var some_url = 'https://usefulangle.com/posts?123#slider'
    
    var url_ob = new URL(some_url);
    url_ob.hash = '#reviews';
    
    // new url string
    var new_url = url_ob.href;
    
    // "https://usefulangle.com/posts?123#reviews"
    console.log(new_url);
    
  • Change hash of the current url

    // document.URL is the current url
    var url_ob = new URL(document.URL);
    url_ob.hash = '#345';
    
    // new url
    var new_url = url_ob.href;
    
    // change the current url
    document.location.href = new_url;
    
  • Note that this will not cause a reload of the page.

Detecting Change in Hash of the Current URL

The window.hashchange event can be listened to know when the hash fragment in the current url changes.

window.addEventListener('hashchange', function() {
	// new hash value
	console.log(new URL(document.URL).hash);
});
How to Get URL Parameters with Javascript
How to Change URL Parameters with Javascript
Reading a URL and its Parts with Javascript
Loading Comments