Progressive enhancement: AJAX navigation menu with jQuery

Progressive enhancement allows everyone to access the basic content and functionality of a given web site using any browser or Internet connection, while also providing those with a more advanced browsers an enhanced version of the site.

Here is an example on how to enhance a starndard navigation bar with AJAX.

Scenario

Example layout for ajax navigation menu
Let's assume that #header, #navigation and #footer are same on every page  and #mainconent, and #sidebar inside the #content are changing on every page.

Problem
The site will have a music player that clients can choose to use while browsing the site. And if they do, we don't want the music to be interupted as they move from page to page.

Solution
Use unobtrusive javascript and AJAX to load content and update the URL using hash in case someone wants to bookmark loaded content.

 

sdf

Javascript/jQuery

We'll use jQuery to bind a click event to the navigation links and use load function to load contents of the clicked page.

Html navigation


Javascript

//FIRST: We'll check if the URL has a hash (was bookmarked) and redirect the user to appropriate page
	 if(window.location.hash!=""){
		var hashpage = window.location.hash.split("#");
		window.location.pathname = hashpage[1];	 
	 }

jQuery

 //bind click event to the navigation links
	 $("#navigation a").unbind("click").click(function(){
		//get href attribute 	
		var page = $(this).attr("href");
		//load all children of the #content div of the clicked page 
		$("#content").load(page+" #content > *");
		//append hash to the url for bookmarking
		window.location.hash="#"+page;
		//cancel browser default so the page doesn't reload
		return false;
	
	 });

Putting it all together

$(document).ready(function(){

	 if(window.location.hash!=""){
		var hashpage = window.location.hash.split("#");
		window.location.pathname = hashpage[1];	 
	 }
	 //navigation
	 $("#navigation a").unbind("click").click(function(){
		//get href attribute 	
		var page = $(this).attr("href");
		//load contents of all children of the #content div
  		$("#content").load(page+" #content > *");
		//append hash to the url for bookmarking
		window.location.hash="#"+page;
		//cancel browser default so the page doesn't reload
		return false;
	
	 });
});

 

Do you like this or find it useful? Drop me a note or treat me to a double-espresso from my favorite coffee shop.

    Comments

    December 12th 2009

    Jay - Great tutorial. I had this idea a while back while using Facebook, but I never got around to coding it. (I'm a bit of a procrastinator :P)

    Reply

    August 8th 2010

    Aleks - Noooooot completly sure I follow you on where you actually tell the page to load only the "content" part...

    Emir - Line 06 of the jQuery section!

    Reply

    Add Comment | Contact me