Search code examples
javascriptjquerytabstoggleslidetoggle

SlideToggle first and last div toggle ones in between


I have been using jquery to create some tabs. Here is my basic code.

JSFiddle

I want to set it so the initial opening of the tab content is a slideToggle but then moving between tabs is a standard toggle then when the user clicks the item to close the items I want it to slideToggle again. So for instance.

Open Tab 1 - SlideToggle, move to Tab 2 - Toggle, move to Tab 3 - Toggle, move to Tab 2 - Toggle, close tab 2 - slideToggle

Is this possible and if so how can I achieve this. I have tried to google this but I can't seem to find the answer.

Thanks in advance for any help.

HTML

<div class="tab">Tab 1</div>
<div class="tab">Tab 2</div>
<div class="tab">Tab 3</div>

<div class="lrgWork"> Tab Content 1</div>
<div class="lrgWork"> Tab Content 2</div>
<div class="lrgWork"> Tab Content 3</div>

JS

    $('.tab').click(function() {
        var index = $(this).index();
        $('.lrgWork').eq(index).slideToggle().siblings('.lrgWork').hide();
    });

Solution

  • How about

    var currentTabOpen=0;//keeps track of what tab is open
    var tabOpen=false;//keeps track of whether a tab is opened
    $('.tab').click(function() {
        var index=$(this).index();
        if(currentTabOpen==index||!tabOpen){//if we're either closing a tab, or opening one,
            $('.lrgWork').eq(index).slideToggle();//use the slide animation
            tabOpen=!tabOpen;//and now the tab is open if it was closed and vice versa
        }
        currentTabOpen=index;//make sure we're keeping track of the opened tab
        $('.lrgWork').eq(index).show().siblings('.lrgWork').hide();//don't use the animation
    });
    

    and see here the working JSFiddle.