2

I have the following HTML

<ul id="tabs">
    <li>1</li>
    <li>2</li>
    <li>etc...</li>
</ul> 

And the following jquery function I am using to append "buttons" for traversing "up" or "down" the list, while only "showing" the current item:

$('#tabs li').first().attr('class', 'current');

$('#tabs li').each(function(i) {
    i = i + 1;

$(this).attr('id', 'tab-' + i);

if(i !== $('#tabs li').size()) {
    $(this).append('<a class="tabPagination next floor-up" rel="tab-' + (i + 1) + '" href="/keyplate/' + (i + 1) + '">Up</a>');
    }
    if(i !== 1) {
        $(this).append('<a class="tabPagination next floor-down" rel="tab-' + (i - 1) + '" href="/keyplate/' + (i - 1) + '">Down</a>');
    }                
});            

$('#tabs li[class!="current"]').hide();

$(document).on("click", "a.tabPagination", function(){
    $('.current').removeAttr('class');
    $('#tabs li[class!="current"]').hide();    
    $('#' + $(this).attr('rel')).show(); 

});

I have another div:

<div id="tower"></div>

What I need to do is add a class to the #tower div, based on the currently selected #tab item. So for example if we are on #tab li = 2, then #tower div would get class="active_level_2". In other words, take the value of 'current' #tab list item and use that to create "active_level_#".

Thanks in advance!

vibe9
  • 33
  • 3
  • 11

1 Answers1

0

You can get the attribute rel and split it to get the last number to use for the active_level_ class. We can also pull $(this) into a variable now since its being used more than once.

jsFiddle

$(document).on("click", "a.tabPagination", function(){
    var tab = $(this);
    $('.current').removeAttr('class');
    $('#tabs li[class!="current"]').hide();    
    $('#' + tab.attr('rel')).show(); 
    for (var i = 1; i <= 6; i++)
        $('#tower').removeClass('active-level-' + i);
    $('#tower').addClass('active_level_' + tab.attr('rel').split('-')[1]);
});

tab.attr('rel').split('-')[1] will get the tab's rel attribute, split the string into two at the - character using split() and get the second part to return the number we want.

Daniel Imms
  • 47,944
  • 19
  • 150
  • 166
  • That's awesome, thanks Daniel. I'm having some trouble with implementing this. It seems that instead of assigning #tower the current class, it's assigning the next class above that. Also, when you go "down" a level it's not removing and reassigning the next appropriate class. To give you a better idea, in practice, what I'm trying to do is mimic the functionality seen [here](http://www.stationsquare.ca/floorplans/). – vibe9 Apr 05 '13 at 06:31
  • So as you can see in the fiddle, the only problem is actually changing the class again when you loop back "down" through the #tabs items. How do I over-write the class? – vibe9 Apr 05 '13 at 06:51
  • That's absolutely fantastic. Thank you so much! – vibe9 Apr 05 '13 at 07:10