views:

190

answers:

3

This is kind of a follow on from a previous question I posted but I've not been able to get it to work..

I'm trying to use multiple sets of tabs (jQuery) on one page.

This is the code I had for one set of tabs which works great:

$('div.tabs div.tab').hide();
$('div.tabs div:first').show();
$('div.tabs ul.htabs li:first a').addClass('current');
$('div.tabs ul.htabs li a').click(function(){
    $('div.tabs ul.htabs li a').removeClass('current');
    $(this).addClass('current');
    var currentTab = $(this).attr('href');
    $('div.tabs div.tab').hide();
    $(currentTab).show();
    return false;
});

To use more than one set on the page I assigned #id's to each tab-set and tried to impliment this with:

$.each(['#tabs-1', '#tabs-2', '#tabs-3' ], function(id) {
    $(id + 'div.tab').hide();
    $(id + 'div:first').show();
    $(id + 'ul.htabs li:first a').addClass('current');
    $(id + 'ul.htabs li a').click(function(){
        $(id + 'ul.htabs li a').removeClass('current');
        $(this).addClass('current');
        var currentTab = $(this).attr('href');
        $(id + 'div.tab').hide();
        $(currentTab).show();
        return false;
    });
});

Obviously I'm doing something wrong here but as a jQuery newcomer I'm stumped!

+1  A: 
$(id + 'div.tab').hide();

Isn't a space missing between the id and the 'div.tab' ? This would evaluate to "#tabs-1div.tab".

Pierre Henry
+1 ............
Reigel
Ahh yes. However, even correcting this has not worked.
Jonny Wood
+1  A: 

okay, so this was not working even with the correct spacing in the code but I have found a much more light-weight solution which works perfectly – jQuery MiniTabs:

/*
 * jQuery MiniTabs 0.1 - http://code.google.com/p/minitabs/
 */
jQuery.fn.minitabs = function(speed,effect) {
  var id = "#" + this.attr('id')
  $(id + ">div:gt(0)").hide();
  $(id + ">ul>li>a:first").addClass("current");
  $(id + ">ul>li>a").click(
    function(){
      $(id + ">ul>li>a").removeClass("current");
      $(this).addClass("current");
      $(this).blur();
      var re = /([_\-\w]+$)/i;
      var target = $('#' + re.exec(this.href)[1]);
      var old = $(id + ">div");
      switch (effect) {
        case 'fade':
          old.fadeOut(speed).fadeOut(speed);
          target.fadeIn(speed);
          break;
        case 'slide':
          old.slideUp(speed);  
          target.fadeOut(speed).fadeIn(speed);
          break;
        default : 
          old.hide(speed);
          target.show(speed)
      }
      return false;
    }
 );
}

Using this code you can then add:

$('#tabs-1').minitabs();
$('#tabs-2').minitabs();
$('#tabs-3').minitabs();

And everything works perfectly!

Jonny Wood
A: 

Is there a way to make use of browser history in the minitabs script? i.e. let the back button load the previously viewed tab.

Sam Nabi