Using Hash Urls with jQuery Example

Share this article

Many modern web apps these days use hash urls to add uniqueness (like a page tag, section, action etc…) to a page without refreshing it youn can identify it. This is following on from Getting Url Parameters Using jQuery to pass dynamic data to the page through through the URL. Which is still widely used on the WWW.

window.location.hash vs document.URL

Let’s take a quick look at both and below is a regex which you can use to grab the hash tag.
//using window.location.hash
$.fn.urlHash = function()
{
  return window.location.hash.replace('#','');
};
$.urlHash();
Important: location.hash is not safe for IE (including IE9). Also if your page contains an iframe then after manual refresh inside iframe content gets the old location.hash value (for first page load) while manual retrieved value is different than location.hash so it might be best to retrieve it through document.URL.
//IE Proof - URL Hash Grab - returns complete hash value
$.fn.urlHash = function()
{
  return document.URL.substr(document.URL.indexOf('#')+1);
};
$.urlHash();
So as an example to extract the dayofweek hash tag value you would do it like this:
//in context - extract dayofweek hash
//eg  url#dayofweek1 would return 1
if (document.URL.indexOf('#dayofweek'))
{
    week = parseInt(document.URL.substr(document.URL.indexOf('#')+1).replace('dayofweek',''))-1;
    $resParent.eq(week).showResources();
}

Another Decent Way

This is another decent way using a heavier regex (the pound sign is optional, since .match() never returns null).
var match = location.hash.match(/^#?(.*)$/)[1];
if (match)
{
   //do stuff...
}

Fails…

var hash = location.hash.match(/#(w+)/)[1];
Issues: Returns wrong results when there is any non-latin or non-alphanumeric character in the hash. For example, for the hash #foo@o#bar$%huh hello, just “foo” would be returned. Throws a TypeError when location.hash is empty, since .match() will return null
var hash = location.hash.split('#')[1];
With the same test hash, it would at least get the “foo@o” part, which means it only fails when the hash contains a pound sign. When there’s no hash, it doesn’t throw an error, although it returns undefined instead of the empty string.

Reference Material

Get your hash — the bulletproof way

Frequently Asked Questions (FAQs) about Hash URLs

What is a hash URL and why is it important?

A hash URL is a URL that includes a hash (#) symbol followed by an identifier. This identifier is used to point to a specific section within a web page. Hash URLs are important because they allow users to directly navigate to specific content on a page, without having to scroll through the entire page. This is particularly useful for long web pages with multiple sections. Additionally, hash URLs can be used to maintain state in a single page web application, where the hash changes to reflect the current view.

How can I create a hash URL?

Creating a hash URL is quite simple. All you need to do is append a hash (#) symbol followed by an identifier to your URL. For example, if you have a page at www.example.com and you want to create a hash URL that points to a section called ‘section1’, your hash URL would be www.example.com#section1.

How can I use jQuery to manipulate hash URLs?

jQuery provides several methods to manipulate hash URLs. The ‘hash’ property of the ‘location’ object can be used to get or set the hash part of the URL. For example, to set the hash to ‘section1’, you would use location.hash = 'section1';. To get the current hash, you would use var hash = location.hash;.

Can I use hash URLs for AJAX navigation?

Yes, hash URLs can be used for AJAX navigation. By changing the hash, you can load different content without refreshing the page. This is often used in single page applications to create a smooth user experience.

How can I detect hash changes with jQuery?

jQuery provides the ‘hashchange’ event, which is triggered whenever the hash changes. You can use this event to run code whenever the hash changes. For example, $(window).on('hashchange', function() { /* Your code here */ });.

Are there any drawbacks to using hash URLs?

While hash URLs can be very useful, there are some drawbacks. One major drawback is that they can cause issues with search engine optimization (SEO), as search engines may not index the content associated with the hash. Additionally, hash URLs can cause issues with analytics, as they are not always tracked as separate page views.

Can I use hash URLs with anchor tags?

Yes, hash URLs are often used with anchor tags to create ‘jump links’ that allow users to navigate directly to specific sections of a page. The hash in the URL corresponds to the ‘id’ attribute of the anchor tag.

How can I remove the hash from a URL with jQuery?

You can remove the hash from a URL by setting the ‘hash’ property of the ‘location’ object to an empty string. For example, location.hash = '';.

Can I use hash URLs to store state information?

Yes, hash URLs can be used to store state information. This is often used in single page applications, where the state of the application is stored in the hash. This allows the user to navigate back to the same state by using the back button or by bookmarking the URL.

How can I use hash URLs for deep linking?

Deep linking is the practice of using a URL to navigate directly to a specific piece of content within a page. Hash URLs are perfect for this, as they allow you to link directly to a specific section of a page. To use a hash URL for deep linking, simply append the hash and the identifier of the section to your URL.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week