We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies.If you want to ask for a budget, we hare available for hire!.
Creating AJAX websites based on anchor navigation
November 26th, 2008Hi again folks! As you can see, the amount of publications is increasing daily, it is because we realized that everyday more people come to read read the blog to learn about web design. So, we decided to spent more time to share our knowledge with you.
In this tutorial we will see how to create an AJAX website without lose the reference to the URL. What is that not lose the reference? If you have created some full AJAX website you have realized when you change the web content, the URL is not updated, so, the URL reference is lost. Services like Gmail uses it to increase the navigation’s user experience.
It can be very very useful to create awasome ajax based sites such as Gmail web application from Google, users will appreciate it so much. As always we will use jQuery to do the ajax part easier for all
Update: Now with loading division while you are waiting to load the current section!
You can test a working live example over here:
Tested in: Firefox, Internet Explorer 6 & 7, Opera, Safari & Chrome.
Anchors make it easier and better
What’s the solution to this strong trouble? Just use anchors on your URLs. For those who don’t know, anchors are used in HTML to fix places in the web document and let you move the user between them. The anchors are representated in the URL with # and can be changed in the client side with javascript. Then we can use this feature to update the URL every time you change the section through AJAX.
Another big problem that anchor navigations fixes, is the use of back button in your browser. Browsers don’t save the AJAX petitions in the history, so you can’t navigate to the back or next sections. However, with the anchor navigation method you can do it. This is used by many advanced websites as GMail or Google Reader. I don’t wait you more and let’s get down to build the example.
So anchors will help us:
- To change sections without reloading the current page
- To use AJAX petitions without losing the history (back button on your browser!)
- To increase the user experience SO MUCH
Step 1: The xHTML layout
In this tutorial the cool part isn’t here, so we will create a simple and clean layout for our purpose:
[code="html"][/code]
As you can see we have: menu division & content division. In this last division, the content division, will be used to load the content of each section via AJAX. In the other hand, we have the division called loading that will be showed when the section is being loaded via ajax.
Step2: Styling out web site
Now a little CSS to beautify a little the content
[code="css"] @CHARSET "UTF-8"; /******* GENERAL RESET *******/ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { border:0pt none; font-family:inherit; font-size:100%; font-style:inherit; font-weight:inherit; margin:0pt; padding:0pt; vertical-align:baseline; } body{ line-height:14px; font-size: 12px; background: #fff; font-family: Arial, Verdana, Helvetica, sans-serif; margin:0pt; cursor:default; } table{ border-collapse:separate; border-spacing:0pt; } caption, th, td{ font-weight:normal; text-align:left; } blockquote:before, blockquote:after, q:before, q:after{ content:""; } blockquote, q{ quotes:"" ""; } strong{ font-weight: 700; } .clear{ clear: both; height: 0; visibility: hidden; display: block; } /******* /GENERAL RESET *******/ /******* LOGO *******/ #logo{ text-align: center; margin: 15px auto; } /******* /LOGO *******/ /******* MENU *******/ #menu{ width: 412px; margin: 30px auto 0; } #menu ul{ text-align: left; } #menu ul li{ float:left; list-style: none; list-style-position: outside; } #menu ul li a{ color: #7c7c7c; margin: 0 1px 0 0; float:left; } #menu ul li a img{ float:left; } /******* LOADING *******/ #loading{ position: absolute; top: 0px; margin: 0pt auto; padding: 0.5em; background: #ff8a00; font-weight: 700; color: #fff; display: none; } /******* /LOADING *******/ /******* /MENU *******/ /******* CONTENT *******/ #content h1{ color: #6fa5fd; font-size: 24px; line-height: 1em; margin: 1em; } #content p{ color: #7e7e7e; font-size: 12px; line-height: 1em; margin: 1em 1em 1em 2.5em; } /******* /CONTENT *******/ [/code]
Nothing special over here, just hide the loading division and adding some style. Continue reading guys!
Step3: The Javascript Core
This is the most important step for this example. With javascript we create a listener that check when the URL anchor is changed and load the appropriate section. This listener simply is a function which is executed every 300 miliseconds and it checks the property document.location.hash has changed.
In Javascript you can know the current anchor getting the value of document.location.hash. This property is writable so you can modify the value like you need it.
So create a js file called “core.js”. The code is as follows:
[code="Javascript"] //On load page, init the timer which check if the there are anchor changes each 300 ms $().ready(function(){ setInterval("checkAnchor()", 300); }); var currentAnchor = null; //Function which chek if there are anchor changes, if there are, sends the ajax petition function checkAnchor(){ //Check if it has changes if(currentAnchor != document.location.hash){ currentAnchor = document.location.hash; //if there is not anchor, the loads the default section if(!currentAnchor) query = "section=home"; else { //Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2 var splits = currentAnchor.substring(1).split('&'); //Get the section var section = splits[0]; delete splits[0]; //Create the params string var params = splits.join('&'); var query = "section=" + section + params; } //Send the petition $.get("callbacks.php",query, function(data){ $("#content").html(data); }); } } [/code]
As you can see, we show the loading division while user is waiting for data from the new selected section.
Step 4: creating a simple PHP script to serve callbacks requests
This is a simple and easy file that loads the required section sent in the callback request from AJAX:
[code="PHP"]You are at home
Wellcome to the new tutorial from yensdesign.com. Enjoy it!!
Look at the URL! It changes but page doesn't reload!!
The tutorials section is good for your brain
This tutorial can be very very interesting in dynamic projects, play with it
Web design at yensdesign.com
And remember: Visit us!!! yensdesign.com
Coding
Hellow World!
Unknown section
You are in an unknown section!
} ?> [/code]
NOTE: We have used the sleep() function to stop some seconds the PHP script to simulate a high loading charge, letting you see the loading division
Step 5: Trying out our AJAX website based on anchors
That’s all guys, I hope you can use it for your personal projects to increase the users experience and to be the next Gmail Killer Application hehe
You can try the tutorial online here to see how It is working and download here all sources.
One more thing guys! If you don’t have already your plusmusica.com and want to try it, send me and email or just post a comment! See you on next tutorial guys and thanks for your comments
Visit PsPrint and learn how you can create effective and excellent-looking die cut stickers.
It is a good idea to invest in a high quality Security Camera while working away from home in order to protect yourself from theft and burglary. You can find several video tutorials on how to set up a home security system on youtube.
Enjoy this post?
Your vote will help us to grow this website and write more entries like this one :)
We available for hire! — Need help with a web or mobile project?
From yensdesign we develop technology projects based on web apps, mobile apps, consulting and databases. We are young and hard workers, passionate about innovation and focused in new technologies. We try to help you, sharing our knowledge acquired on worked projects, while helping the community and showing our capabilities.If you want to ask for a budget, we hare available for hire! Don't doubt in get in touch with us!.
Great TUTORIAL, thanks so much !
Ey JCargoo so fast! ^_^ thanks for your comments!
Hi! I don’t much about js and jQuery, even though I find them fascinating…so bear with me if the question is stupid…but why/where is the ‘s’ posted from the javascript code to the server?
There is no post, there is a GET petition to catch the content for the division id “content”.
It’s that part from core.js (at the end of the file):
//Send the petition
$.get(“callbacks.php”,query, function(data){
$(“#content”).html(data);
});
In addition: You request a GET from the callbacks.php and it responses with the html content, right?
Thanks for the explanation! I promise I will follow your next tutorials and try to be smarter
i wish there was “loading…” indicator too
Ey! nice idea sumit, I will update the tut soon
@sumit: Done
Although i find the task you set yourself to explain in this tutorial very appealing, i’m unconvinced by the solution you propose. To be more specific, i find it very odd to run a setInterval every 300ms permanently. It sounds much like Flash 5 ‘onEnterFrame() event.
After all, why don’t you just use each link’s “click” event, and fire up the behaviour on click? That will ease your browser’s CPU usage…
Hi pixeline! Thanks for your comment. Let’s say you that actually I have not found a better way to perform this method. I understand your proposition of use only click events, however, it not work well because you can’t use the back/next button of your browser. In addition, using only events clicks, the page will not be refresh when you change the URL manually. Both are very important features to the increment the user experience.
I hope you are convinced with the above points
Thank you so much.
[...] See the original post [...]
Thank u r information
While this is a good tutorial and teaches some decent ideas, in order to get the most solid cross-browser behavior its recommended to use JSSM (jquery based) or Really Simple History (independent).
Hi Paul! Thanks for your input. This tutorial is only a initalization to the users, so, it can be much improved. I only have wanted demonstrate readers that sometimes implement advanced fetaures is not as complicated as it seems and 3th-party libraries are not always necessary. Using 3th-party usually implies add extra functionality which is not necessary.
Bye!
nice nice nice !! awesome Ajax Tutorial. Using anchor, we can define each of page section. Not so bad for SEO
there is some posible better solution is to use adaptative timers, instead of fix wait time of 300ms. Use the same method, but after waiting 300ms if there is no ajax call, increase the wait time for the next one, for example 600, if no call then 1200 and so on. If a ajax call is done, just reset the wait time back to 300ms. Something like that is what google use in gmail.
Ey jazcks very interesting and optimized solution, thanks!!
Hi. I’m trying to use this with Thickbox, but the image links open in the page, not in the Thickbox. I’m a newbie in JQuery world… can anyone help me?
Hello… great tutorial…
I tried to change links, for example:
from to
and location change from http://www.mysite.com/#tutorials to http://www.mysite.com/tutorials/
If i press this link it tries to go to a folder named tutorial on my webserver (logic).
It`s posible to change something in “core.js” to work?
(Instead of “#tutorial” to get from location “tutorial/” without going to another location).
Thanks !(sorry for my english)
@Pinte: Thanks! You need to use the anchor, read one more time the tutorial and the title
But maybe you can use a return false at the end of the event that you want… But it’s better use anchors for this kind of navigation
Hi,
can a search engine find the content that is generated by the ajax?
Im not an ajax pro, but what is the best solution, if i want to change multiple contents, maybe in the navigation?
Thanks for help
Ey vardump! The short answer is: Yes you can creating hrefs and returning false in your javascript code.
But check out the long answer: http://www.softwaredeveloper.com/features/google-ajax-play-nice-061907/
Nice article
Thanks for the article, I’ve wondered how Gmail worked since the upgrade. I wish I was savvy when it came to ajax development, I have so many good ideas… just not the skill to pull them off! *sigh*
:0)
I noticed you mentioned you could send an invite to the plusmusica.com site. If you have any invites left, would you send me one?
Thanks again!
Yeah of course SirG here you have and thanks you too!
Great tutorial! Very useful, thank you
You forgot to include <div id=”loading”>Loading…</div> in your example layout in step 1, may confuse others looking for thhe loading container
Cheers!
I have been looking for an example exactly like this for some time. it is 99% perfect, but the 300ms wait makes it unusable, as I’m looking to make a very quick portfolio site in which javascript swaps preloaded images, but used anchor-based navigation so that any image can be called up directly using a URL. site.com#image1, site.com#image2.
would it be possible to use an onclick event to change the content immediately, and then 300ms later have that action basically do what the onclick event did? it would be redundant, but it would make it snappy and make it possible to call the page via a URL.
am i on the right track?
thank you in advance.
Hi John Healy! Do you really think that 300 milliseconds are noticeable? You can test the example and you notice that the behavior is almost instant.
Obviously, you can use mouse click event to force your script execution using the [element].onclick, but I think you don’t need it
Nice tut, but i have one question. I’m making a website with a jquery smooth scrolling between anchors. I’ve tried to implement this into one div for testing, but because of anchor loading it want work well. First problem was javascript conflict, after fixing that content was loaded but navigation using anchors dont work. Always shows ” Unknown section You are in an unknown section!”.
I supose that loading using anchors is the problem, is there any other way to load content?
Hi
GREAT article! thanks a lot for sharing…
But.. are you sure that its SEO friendly?
I’ve entered the link that you’ve posted here ( http://www.softwaredeveloper.com/features/google-ajax-play-nice-061907/ ), and on that article there’s a link to a site that shows pages the way the google bot “sees” it… (www.seo-browser.com).
I’ve tried one of the anchored links from your example on that site, and unfortunately – the output didnt contain the new AJAX content
Here’s the link – http://www.seo-browser.com/index.php?user_agent=2&address=http%3A%2F%2Fwww.yensdesign.com%2Ftutorials%2Fanchornavigation%2F%23coding&action=Parse+URL
It should contain “CodingHellow World!”, but it doesnt…
By the way, is your method any different than the one mentioned here in the comments (http://trac.nathanhammond.com/jssm/ ) ?
Thanks again!
David
Hi David! Do you really has readed the article (http://www.softwaredeveloper.com/features/google-ajax-play-nice-061907/)? The article gives you tips to help you making AJAX enabled and SEO friendly web sites. Really it’s a hard task, you should contemplate when you can lose SEO visibility in order to win AJAX capabilities, for example, GMail uses this feature, but GMail doesn’t need SEO position because it’s totally private.
Good luck!
I tried this in Internet Explorer 7.0.5730.11 and it didn’t work.
The url changed but the content did not.
m
nice tut, thx alot! like marc said dosnt work in IE. anyway, Lloyd got right, im confused bout that loading div!? dosnt shown up when i include it. any core.js manipulation needed!?!
At first thx for the tut but how can i use this kind of navigation for HTML pages or am i too stupid and i just can do this with php based sites. it’ s because i want to make a portfolio site, but on one page i need a html page for loading special scripts on it..
@GGrag Checkout this tut, maybe it’s better for your purposals: http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/
thx, Adrián
@adrian. Thx for bringing me here. I think this is what i’ve been looking for. Gotta try it. Thx again.
hey! very nice tutorial. but still, i can’t find the “loading.. image”
Doesn’t work here in MSIE7, either.
Hi. Thank you for the tutorial. I tried running the downloaded code, but it didn’t work. I put some alerts to troubleshoot it and I found that it did call the checkAnchor function but nothing is happening on the
//Send the petition
$.get(“callbacks.php”, query, function(data){
$(“#content”).html(data);
});
I tried adding an alert inside the function(data) and looks like the callbacks.php is never called.
I put the callbacks.php in the same directory path as the core.js.
Looking to hear from you on the solution to this.
Hi. Disregard my question. I am able to get it to work now. The callbacks.php needs to have the php define in the <? line. So, it would be <?php.
Thanks.
This looks fine to me in IE6, IE7 and IE8. I’m not using the standalone versions, though. Maybe that could be why above commenters said this wasn’t working for them in IE. I’d be curious to know.
@Mark I am not sure… but It works fine on IE7 and 6 for me too…
Also, is it possible to make this degrade gracefully if javascript is turned off? None of the content loads for me with javascript turned off.
The code you have posted in the examples on this page is slightly different from the code in the example you link to at the top of this page – this is why above comments say they can’t get the “loading…” box to appear.
To add the loading feature to the example code above, do this:
- in the html code in step one, add this as the very fist line of the body
loading…
- in the javascript core code in step three, in the very last part under the comment //send the petition, add $(“#loading”).show(); as a first line and $(“#loading”).hide(); as a last line.
Hmm, the div code got mangled in that comment when I posted it.
In the html, add the word “loading” without quotes wrapped inside a set of div tags as the fist line of the body. The js code above stands.
There seems to be a problem with the back button in internet explorer. Is there any way to fix that?
~ Rob
When the site is longer than the screen display, clicking on an anchor makes the browser to scroll down to have the anchor on top of the page, which in this case is undesirable… Is this avoidable?
I got the same problem with the anchor, it will auto scroll down.
~ The back button is fixed in IE 8
[...] Creating AJAX websites based on anchor navigation [...]
[...] Creating Ajax Websites Based On Anchor Navigation: [...]
Thanks for the tutorial, Adrián! Is it possible to give the URL an ID as well as an anchor?
I need to display data from a DB.
e.g. homepage.php#home&id=1 – this doesn’t seem to work – there is something referring to this string callback in the core.js file (URL/#main&id=2) – do I find the answer there?
I am new at this – perhaps there is an alternative answer?
Any help appreciated!
~ R
@Rich Hi! I am the developer of this javascript tutorial, so, I can help you better.
If you review the “checkAnchor()” function, you can see that the anchor text is splitted and each parameter is sent to the server in an AJAX callback. At first, you can check if this data is sent to the server written the above code into your server-side script:
print_r($_GET);
Bye!
Thanks for the quick reply, Iván! I think I will need to play around with this a little, I am still a little lost! Sure I’ll get there though.
I found something nicer http://fancyload.com
fade transitions, loading image, nice URL ex: #value1/value2/value3
How about this: add click triggers to the links to immediately load the requested section and just call `checkAnchor’ from `$(document).ready’ in case the section is not accessed through a click; that way we avoid the use of the `setInterval’ function.
Thanks.
Nevermind, that won’t work if the user clicks the back/forward button… Do’h
The `setTimeout’ function takes care of that, but that doesn’t seem to be the best solution.
Thanks.
Hi.
Thanks for this tutorial but i have a problem with the IE.
If i use the back and forward buttons the document.location.hash isn’t updated.
So i can’t use the buttons to navigate through my site.
I also tried the example code but there is the same problem.
Any tips?
[...] But now we can solve this by this tutorial: http://yensdesign.com/2008/11/creating-ajax-websites-based-on-anchor-navigation/ [...]
[...] "angesprochen" werden konnten. ich versuchte beim umstieg auf ajax das problem mit ankern bspw. index.php#section zu l
thanks
Hi Guys, great and SIMPLE!!! tutorial…
though i’m still lost with ajax, can you do $POST with this script?
and i have the same problem as Rich with parameters, are they being passed to the loaded file?
thx.
[...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Monday, June 8th, 2009 at 4:11 am and is filed under Javascript Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]
The provided demo does not work properly with the back button on IE 6. Try these steps.
- Open IE and go to the demo provided at http://www.yensdesign.com/tutorials/anchornavigation/
- Click all 4 of the boxes. The URL hash changes and the content changes. this works
- Click the back button. The URL hash changes, but the content does not change at all.
Does anyone know of an IE event that is fired on the page when the back button is pressed and the page is loaded? It’s loading from the cache. If we can figure what event is fired, we should be able to solve the IE 6 problem.
Thank!
Hello Chris
my project source http://www.habibustun.com/facebooktarzi/index.php this run on FF, but not run IE.
Do you have a solution that can produce? thanks.
[...] i found this tutorial regarding how to create website anchor with ajax here is the link ( http://yensdesign.com/2008/11/creati…or-navigation/ [...]
Very nice tutorial. I have two questions if anybody can help
1. DOES Google index the content loaded via ajax? (injected in a DIV)
2. Is there a way to DIFFERENTIATE the menu anchor from a regular anchor? Because I use, for example, an anchor to navigate ‘top’ on the same page BUT when I click it, it behaves as an menu-item (and try loading the content via ajax for that value of the anchor instead ‘using’ it to navigate top).
I have a problem about the AJAX anchor-navigation in IE with XML/XSL.
I am builidng a website with XML/XSL, there are 2 pages: A and B.
Both are using AJAX anchor-navigation.
If a user surfs in page-A, the AJAX anchor-navigation works fine.
However, if the user changes the url from page-A to page-B, all the history of AJAX anchor-navigation of page-A will lose when IE constructs the HTML through XML/XSL.
That’s mean if the user go back to page-A from page-B, he will just see the most beginning state of page-A.
Only IE has this issue, could you suggest any solution?
Thank you very much.
Hi,
i’ve got a problem with sending forms. I mean that data sent from a form can’t be read by a script and i got that error “Notice: Undefined index: login in …”
How can i fix it?
[...] 37)Creating Ajax websites based on anchor navigation [...]
Great tutorial…
Is there a way to hide the query from showing in the address bar or better still use a POST?
Hello there, thank you for this script but I am having one problem…
I have scripts on the page (callback.php): some of my own scripts and also Adsense & Analytics codes which I can’t access::, and when the Ajax loads the page (callback.php) it keeps refreshing the page every second, and doesn’t seem to work with a ()script embedded on the callback.php page…
What can I do to have scripts on callback.php and still load it via Ajax anchor navigation?
Please help…
nice tutorial.. thanks
Hi there,
I’ve found this article extremely helpful.
Just thought i’d ask though, why in the first 3 lines of core.js, have you chosen to use setInterval? is there a specific reason?:
$().ready(function(){
setInterval(“checkAnchor()”, 300);
});
I found that it broke anything else on the site that required some sort of interval e.g. sliders. Incase anyone else is experiencing this, to get around it I just added onclick=”checkAnchor” to all of my hrefs and commented out lines 1-4 in core.js.
This is a great idea i will implement in my projects. Those of you who have problem with IE7 should upgrade cos it worked on mine. Please if you are running the demo on your local server try and download jquery and include it locally.
thanks
soon you’ll see ma site fully ajaxified…. hats fff….
Thanks a llllllllllllllllllllllooooooooooooooooooooooooooooooooooottttttttttttttttttttttttttttttttt
m going to make this for my upcoming website
thanks…..
Come to see this valuable wonderful web pages
Come to take a look at this specific fine web page
[...] Creating AJAX websites based on anchor navigation [...]
[...] 4. Creating AJAX websites based on anchor navigation [...]
Hi, its awesome tutorial…
when i load a page through callback, where it uses some php code from the original page, it doesnt load the php variables… why? and how to resolve it…
Thank You
Another solution is: http://api.jquery.com/event.preventDefault/
This doesnt require much work it just involves using jquery’s inbuilt function!
This is used by many advanced websites as GMail or Google Reader. I don’t wait you more and let’s get down to build the example.
Does your site have a contact page? I’m having trouble locating it but, I’d like
to send you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing. Either way, great blog and I look forward to seeing it grow over time.