Accessible Ajax Tabs With MooTools

Ajax tabs (JavaScript tabs that only load tab content on request) have a couple problems:

  • Can't be bookmarked.
  • Search engines can't index the tab content.
  • Inaccessible for users with JavaScript turned off.

They are, in many ways, frames for the web 2.0 generation. But they don't have to be. In this tutorial, I'll demonstrate how to make search-engine-friendly, handicap-accessible Ajax tabs using MooTools and PHP.

UPDATE: A new version of this script is now available.

Check out the demo or download the project files.

Note: This demo is written using the MooTools 1.2 Beta Release.

The trick to accessible JavaScript is to make your pages work without JavaScript - then add JavaScript on top. Easy, right?

Without JavaScript

Let's start by making a tabbing interface that uses query string variables to update the tabs. View the demo before JavaScript is added. Success! This takes care of bookmarking, search engines, and users with JavaScript turned off. Now let's add some Ajax magic.

With JavaScript

View the demo after JavaScript is added.

The JavaScript needs to:

  1. Modify the tab links.
  2. Activate the tab and make an asynchronous request.

Modify the tab links

First we stop regular link events. Otherwise, the user's web browser will just link to the query string variables as it does with JavaScript turned off. Then we add a JavaScript event to the tabs, passing the ID of the tab to a function.

  1.  window.addEvent('domready', function(){
  2.    $('tabs-nav').getElements('li').each(function(i) {
  3.      i.addEvent('click', function(event){
  4.        event.stop();
  5.        Tab(i.get('id'));
  6.      });
  7.    });
  8.  });

Activate the tab and make an asynchronous request

Since we don't know the ID of the previously active tab, we go through all of the tabs and remove the CSS class that visually highlights them (a class called "active"). Then we simply add the highlight class to the tab ID that was clicked.

We're going to use that same ID to pass to our Ajax page. For this example, the tab content is hard-coded but you could certainly make it load from your database.

While we're waiting for a response we're going to add a loading icon, or throbber. In the markup, I added a reference to the throbber gif - just so it's pre-loaded in the DOM in time for the JavaScript action. If we don't pre-load, depending on the web browser, an empty image box may appear and we don't want that. Incidentally, Ajaxload is a great resource for loading animations.

  1.  function Tab(key){
  2.    $('tabs-nav').getElements('li').each(function(i) {
  3.      i.removeClass('active');
  4.    })
  5.    $(key).addClass('active');
  6.   
  7.    var req = new Request({
  8.      url: 'tab-change.php?tab=' + key,
  9.      method: 'get',
  10.      onRequest: function() {
  11.        $(key + '-loading').set('html', '<img src=\'images/Ajax-loader.gif\' width=\'16\' height=\'16\' alt=\'Loading\' />');
  12.      },
  13.      onSuccess: function(responseText) {
  14.        $(key + '-loading').setHTML("");
  15.        $('tabs-content').setHTML(responseText);
  16.      }
  17.    }).send();
  18.  }

Final Thoughts

JavaScript tabs can be extremely useful when screen real estate is at a premium. Your decision to use traditional JavaScript tabs, which simply hide or show content when clicked, versus Ajax tabs, which call back to the server to load their content, should be carefully considered. My recommendation is to use Ajax tabs when the tab content is high in file size, particularly images, but your mileage may vary.

Comments

  • mgroves 2 years ago

    This tutorial makes me throb.

  • Eric Taylor 11 months ago

    Can anyone elaborate on why this code does not work with MooTools 1.2.1?

    What would I need to do to get it to work with 1.2.1?

  • Marc Falk 9 months ago

    Thanks for this piece of code, it rocks. But, it doesn't work with MooTools 1.2.2...how can I fix this?

  • Marc Falk 9 months ago

    Oh I found out myself. To get this to work with MooTools 1.2.2, you have to go to tabs.js, go to line 19, 22 and 23 and change the function (text).setHTML(text) to (text).set('html',text)

    Cheers..

  • Jon Plante 9 months ago

    Yeah, this is all indicated in this post here: http://jonplante.com/blog/tabs-in-mootools-1-2/

  • Steve D 6 months ago

    Jon, as a relative novice to Javascript I am struggling to work out how to include an XHTML page within your tabs rather than the simple text. I was looking for some sort of unordered list in your code, but couldn't find any.

    Do you have an example of an implementation of your tabs with some dynamic content included?

    Cheers

  • Jon Plante 6 months ago

    Steve, for starters make sure you're using the updated version of this script: http://jonplante.com/blog/tabs-in-mootools-1-2/

    An important note: XMLHTTP requests, the guts behind AJAX, likely won't work in a local environment because of built-in security precautions. In other words, you'll need to run this on a web server for it to work.

    Included in the files is "tab-change.php" - this is the server-side script that shows one chunk of html versus another. It doesn't read in separate pages (although you could probably do that with the "include" method) - but it is dynamic. You can see this in action in these two examples (note the querystring variables):

    http://jonplante.com/demo/tabs-1-2/tab-change.php?tab=tab-1

    http://jonplante.com/demo/tabs-1-2/tab-change.php?tab=tab-2

    The JavaScript is simply accessing this page (tab-change.php) with an XMLHTTP request.

  • Steve D 6 months ago

    Thanks Jon, I am using your updated script and my test page is running on my web server;

    skiddmark (dot) com (forward slash)tabs12 (forward slash) index (dot) php

    I am looking to re-create the same kind of tabbed content as used on Kontain's home page;

    So need to populate each tabbed frame with galleries of photos, videos, music, people etc.

    It's not yet clear where I add the links to these html pages within the files you have created. I had originally assumed that I would amend the 'tab-change.php' file to include calls to the pages I wish to load, but I am still getting my head around where to add this and how to code it.

    For example one of the pages I wish to load into a tabbed frame is..

    skiddmark (dot) com (forward slash)socialnetwork (forward slash) browse_music (dot) php

    ...which will show the music that has been uploaded within the community. It should be pretty simple.

    Any quick suggestions would be much appreciated.

    Cheers

  • Jon Plante 6 months ago

    In tab-change.php you'd change it to something like:

    if ($varTab == "tab-1") {
    include("browse_music.php");
    }
    if ($varTab == "tab-2") {
    include("something-else.php");
    }

  • JC 4 months ago

  • Jon Plante 4 months ago

    Thanks, JC. This has been fixed.

  • Deep 4 months ago

    I dont know why the demo is not working in IE 7 with Javascript ON.

  • Jon Plante 4 months ago

    Deep, that's probably a bug in the MooTools 1.2 Beta.

    Please refer to this post (http://jonplante.com/blog/tabs-in-mootools-1-2/), which includes an updated script that works fine in IE7 (and IE6 for that matter).

  • Ashwani 2 months ago

    This tutorial rocks!

Add a Comment

(HTML tags aren't allowed.)


© 2010 Jon Plante. All Rights Reserved. Hosted by DreamHost. Send me a line, or check out my celebrity comics.