What is location.hash?
Location.hash is something in JavaScript that helps people make dynamic or history compatible one-page websites. Still don’t understand? Let me properly explain. This is my first tutorial so bear with me. Lets say you have a website and you need to make 20 or so pages for it but what if you don’t want to make 20 pages or maybe you don’t have enough space on your hosting to have that many pages? What if you just want one page to dynamically load any specific page and have the ability to go back and forward. What if you’re building a web-app? If the app refreshes, It screws up the app-like feel. This is where location.hash comes in handy.
To build build a dynamic one-page website, you need to use JavaScript to read the hash value in the URL to determine what page to load and then use JavaScript to load it.
What is a hash value?
I don’t know if it’s called a hash value. I just call it that. A hash value is the string of text in the URL after the hash(pound if you’re American) symbol. For example, http://www.mywebsite.com/#hashvalue. If I had a dynamic one-page business website and you click the “About” button, the URL will go from http://www.bizsite.com to http://www.bizsite.com/#about. That will tell the website what page to load.
How to actually use location.hash?
Don’t rush me. I just need to make you you understand everything before we start. Before we actually start coding(or steal my code) you need a few things. First, you need an html editor like Dreamweaver or notepad++. You could also use notepad or wordpad or whatever Macs come with and save the file as an html file. Next, you also need the JQuery library. It’s not necessary to have it but some of the code I write will require JQuery. You can download the JQuery library from jquery.com. The last thing you’ll need is some programming experience with HTML, CSS, and JavaScript. This is necessary if you want a good looking website and to understand what the hell I’m saying.
One more thing before we start. This tutorial tells you how to use location.hash. I do not show you how to build a complete website. If you want to know how to make a website, then you’re in the wrong place. Also I am showing you my method of doing this. There are other ways of doing this.
Compatibility note: This works in all browsers except iPhone. onHashChange is not supported on mobile safari. It probably works on the newer iPhones but not the original. If you are building a web-app you need to replace the onHashChange code to something iPhone compatible. I don’t know much about web-app development so I can’t help you.
Got everything? Good. Lets get started.
First I’m going to show you how to create a link with a hash value. Create a link and in the href attribute, put “#whateveryouwanttoput”. It should look something like this: <a href="#myhash">Link</a>. Now save your file as a .html file and test it in the browser.
You should see a link like this: Link. When you click it, the only thing that changes is the URL. Awesome right? Now lets get to the real coding. In the tutorial, you will be using relative links not hash links. Continue reading for more information.
Actually using location.hash.
To build a proper one-page website using location.hash, you should do a check when the page first loads to see if there is a hash value available. This will come in handy if someone bookmarks a specific page or links directly to that page. What you need to do is check if a hash value is available or not. You do the check once on the onLoad event or JQuery’s ready event.
Here’s the code I created:
<script src="path/to/your/jquery.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
// The following script was created by Dakota Wyatt from Dcoinc.net.
$(document).ready(function(e){
if(location.hash){
// We got a hash value! Lets take off the hash and smoke it.
var newhash = window.location.hash.substring(1);
// place your code here to change the content.
// alert(newhash);
// uncomment the above code to see if it works.
}else{
// no hash value
// alert("No hash available.");
}
});
</script>
This code checks if there is a hash value present during it’s first run. If there is, we can change the content on the page to it’s proper page content. If not, either do nothing or load the home page. I use substring to remove the hash symbol from the location.hash for proper reading so if I go to the store page directly, it will find the hash value and remove the hash symbol and it will come out as just “store” instead of “#store”. If you need the hash symbol for some reason, Just remove the “.substring(1)” part. You can test it by uncommenting the alerts and opening the file in a web browser and at the end of the URL, add a hash symbol and type in some text and press enter. If it does nothing, refresh the page. If it still does nothing, check the code to make sure there are no errors.
Time to explain the code.
The $(document).ready(…); is to tell the code not to run until the DOM is ready. Without this, the code will run before anything is ready and the code won’t work. This requires JQuery to run. If you don’t wan’t to use JQuery, Replace $(document).ready(…); with
document.onLoad = function(){
// The code in the middle goes here.
}
I think that’s how it’s supposed to be.
if(location.hash){…} checks if there is a hash value. If there is, you can run a function or any code you want.
var newhash = window.location.hash.substring(1);
The code above is the variable so you can easily load a page dynamically by using the load function or call a function that places specific text in the content area.
Next is to hijack the links.
Hijacking links means to stop the link(or links) from going to it’s original destination and make it go somewhere else or nowhere. Why do we need to do this? Simple. What if you want to make a dynamic one-page website and some asshole with JavaScript disabled comes to your website and is pissed off because your website doesn’t work. The URL might change if you add a hash symbol in your links but it won’t do anything else. We want to have static webpages for losers people without JavaScript and still have our fancy site for the people who kept JavaScript enabled. If you had a link like http://www.myfancysite.com/about with JavaScript we can redirect the user to http://www.myfancysite.com/#about. That way the page wont refresh and Anti-JavaScripters can still somewhat enjoy your site. The code I’m about to show you only works with relative links without extensions. Examples of proper links:”home, about, donate, etc”. Examples of improper links: “home.php, about.html, http://www.mysite.com/donate”
To do that is simple. Here is the code. Place this inside your onLoad or ready event
$("a").click(function(e){
e.preventDefault();
window.location.hash = $(this).attr("href");
});
With this code, it takes all of the links and prevents them from leaving the page. The only thing it will do is change the hash value of the page you want to go to. But what if you only want certain links to be hijacked? Easy. If you only wanted navigation links for example to be dynamic then put all of the link in a div or span and give it an id of nav or whatever you want and replace “$(“a”)” with “$(“#nav a”)”. So now all of the links the the nav element will be hijacked.
Now to explain this piece of code:
$(“a”).click(function(e){…}); is used to run a piece code when a link is clicked. In this case, when you click a link, it doesn’t go to its original location. It stays on the same page and adds a hash value in the URL. The part that is bolded requires JQuery. If you don’t want to use JQuery, you can replace $(“a”) with something like document.getElementById("div") or something like that I don’t know, I’m not a JavaScript expert.
e.preventDefault(); is a JQuery event and it’s used to stop the link from going to its set destination. That way it won’t leave the page when you click a link. This is a JQuery event meaning you need JQuery and I don’t know the JavaScript equivalent except maybe adding “return false” in the onclick attribute on the link like “<a href=”http://www.website.com/epicwebpage” onclick=”return false”>Epic page</a>”. People without JavaScript enabled don’t have to worry about it because “return false” will be ignored. Here is more info for preventDefault.
window.location.hash = $(this).attr(“href”); changes the URL by adding a hash symbol and adding the URL from the link. If a hash value is already in the URL(The URL, not the link), it will be overwritten with the new one. This code only works with relative links. If you have full links or links with extensions, You need to either change them or add some code to separate the URL. I might show that later. The part in bold requires JQuery and I don’t know the JavaScript equivalent.
Detecting hash changes from location.hash using onHashChange.
Now all we have to do is to detect whenever the hash changes. When it does, we change the content. To do that, we use JavaScript’s onHashChange event to do that. Before onHashChange was created, People like Google had to use iFrames to keep track of hash change. Now we can detect hash change without iFrames. Using onHashChange is good for keeping track of history. If someone clicks the back button, the user expects to go back to the page before. If it doesn’t do that then your website sucks(no offense). To detect hash change, type or copy and paste this anywhere in your script tag:
window.onhashchange = function(){
// hash changed. Do something cool.
if(location.hash){
var hash = location.hash.substring(1);
// load page
// alert(hash);
}else{
// load home page
// alert("home");
}
}
In the onHashChange event, you can call a function to change the content or change from there. You can use the hash variable to know what page you are on. To test it, uncomment the alerts and add a few link in you webpage and click on them and go back and forth. When you do that you get a popup saying what the hash value is. If there is no hash value, It will alert “home”.
In case you didn’t read the compatibility note above, onHashChange does not work on iPhones. Well at least not old iPhones. Since I don’t have an iPhone 4 or the eventually upcoming iPhone 5, I can’t test it.
Time to explain how this works:
window.onHashChange = function(){…} is used to detect when ever the hash changes like for example, if you click a link or go back and forward.
if(location.hash){…} checks if there is a hash value. This is necessary. If you don’t add it you will get errors when the user tries to go back to the homepage by clicking back.
That is the basics of location.hash take this code and knowledge and build awesome sites with it. I did not do all of the work for you, I just showed you how to detect hash change and react to it. Everything else you must do on your own. If you need help, Leave a comment and I will try to help you.
Before I forget, here is the full code:
<script src="path/to/your/jquery.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
// The following script was created by Dakota Wyatt from Dcoinc.net.
$(document).ready(function(e){
if(location.hash){
// We got a hash value! Lets take off the hash and smoke it.
var newhash = window.location.hash.substring(1);
// place your code here to change the content.
// alert(newhash);
// uncomment the above code to see if it works.
}else{
// alert("No hash available.");
// no hash value
}
$("a").click(function(e){
e.preventDefault();
window.location.hash = $(this).attr("href");
});
});
window.onhashchange = function(){
// hash changed. Do something cool.
if(location.hash){
var hash = location.hash.substring(1);
// load page
// alert(hash);
}else{
// load home page
// alert("home");
}
}
</script>
This code will not work by itself. You need to adapt it to your website. If you want to test it first, try uncommenting the alerts on the onHashChange event and one-time check in the beginning.
Should I use location.hash on my site?
You should use it but you should also make sure your website works for people without JavaScript. Why? Because 20% of all Internet users disable JavaScript. Did you know websites like Google, Facebook and Twitter use location.hash but also have support for non-JavaScript users? I don’t know if they use location.hash in particular but I do know they use something similar.
If you want to know how to change the URL itself and not just the hash value, then you need to use HTML5′s pushState. I’ll make a tutorial on how to do that later.
I hope you enjoyed this tutorial an I hope you learned a lot. I tried to make this tutorial as simple yet informative as possible. Later on I’ll make a test page so you guys can see the code in action.