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

ajax-navigation-layout
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.

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;

	 });
});

 

Related Posts: