|
Adding hash values into URLs - The basics |
Building a site that uses AJAX to Asynchronously import content into it? You can take advantage of the URL hash value and some of the functionality it gives you.
By inserting a hash character into the URL you can pick up the string following it and use it as a value in AJAX requests. Also you can create a listener event to check for a hash being added to a URL and use that to activate your custom JavaScript.
This blog entry is an intro to this process, where we deal with adding the hash value into a URL.
First of all we will create a set of hyperlinks that are attached to a JQuery selector.
2 <li><a href="home.cfm" class="ajax-link" id="home">Home</a></li>
3 <li><a href="about.cfm" class="ajax-link" id="about">About</a></li>
4 <li><a href="buy.cfm" class="ajax-link" id="buy">Buy</a></li>
5 <li><a href="contact.cfm" class="ajax-link" id="contact">Contact</a></li>
6</ul>
Note that they have a normal href attribute so that they still work without JavaScript. We'll stop the link actually firing in our function otherwise we will actually change the URL and end out at the page.
Next we create a simple click function.
2 $(document).ready(function() {
3
4 // click event listener
5 $('.ajax-link').click(function(event) {
6
7 // get the id
8 var clickedLink = $(this).attr('id');
9
10 // push it into the url
11 location.hash = clickedLink;
12
13 // debugging alert
14 //alert(clickedLink);
15
16 // stop the regular href
17 event.preventDefault();
18 });
19 });
20</script>
This picks up any link clicked on and gets the id attribute. Next we use location.hash to push the value into the URL. Note that it adds an actual # character to the start of the string.
Lastly it prevents the hyperlink click event from firing so that we don't actually move to the new page.
A short and simple script to add hashed values to a URL. There is a demo of this working here: http://www.mccran.co.uk/examples/jquery-url-hashes/
http://ethehealthadvisor.com/alpha/
http://saragigalau.blog.com/
http://ucapanindahku.jimdo.com/
http://ucapanterindah.webnode.com/
http://katagaulku46.blog.fc2.com/