Ideas – jQuery History

Alex and Aki of Ideas in Food are constantly pushing the envelope of creativity on their blog. They have the same no-barriers approach to what they want on their website, and are never shy about asking for new features or unique presentations.

When they recently asked us to streamline their website, we turned to the amazingly useful jQuery javascript library. We consolidated all of the content into five categories, and added jQuery tabs to separate each page into two or three related sections.

The latest version of the tabs plugin, however, was not pre-configured to track visitors’ click-history (so they could use the browser back-button to navigate) or provide a mechanism for URLs that would link directly to each tab.

After searching through several forums and reading about people who had the same problem, we cobbled together a simple and perfectly-functioning solution.

Many suggested using Asual’s jQuery Address plugin, but the example for tabs on their site is overly complex. We took an idea for a simpler implementation from StackOverflow user Justin Hamade and fleshed it out with some changes so that the browser does not jump to a different spot on the page when a new tab is selected.

The finished code is below.

A simple implementation of browser history and deep-linking with jQuery Tabs 3

  $(document).ready(function() {

        //create tabs
	$("#tabs").tabs();


	// when a tab is selected, update url with the hash
        // but first modify it with a prefix
        // so the page doesn't jump to element with that id

	$("#tabs").bind("tabsselect", function(event, ui) {
	  window.location.hash = "tab_" + ui.panel.id;
	 })

	// for forward and back, pull hash from window url
        // but remove the prefix to get original tab panel id
        // link this to the Asual address.change event
        // which watches for window.location changes

	$.address.change(function(event){
		s = window.location.hash.replace("tab_","");
	  	$("#tabs").tabs( "select" , s )
	 })


  });
This entry was posted in Web Design and tagged , , , , , , . Bookmark the permalink.

Your Thoughts?