Search code examples
jqueryjquery-selectorshiddenvisible

jQuery toggle content, multiple active conditions


I would appreciate some assistance with a content toggle.

I currently have 2 tabs that toggle content - one must be set to focus at any one time and an additional class of active appended when the selected .content-drawer is visible.

Whilst my efforts below work when operating single tabs, the active state doesn't work when switching between states as the :visible condition fires at the wrong time.

Could someone point me in the right direction? Here's my current jsfiddle

    $('.content-drawer').hide();

    $('.tab').click(function() {
        var target = $(this.rel);
            $('.content-drawer').not(target).slideUp();
            target.delay(500).slideToggle();
            $('.tabs > li.focus').removeClass('focus');
            $(this).parent().addClass('active focus');

    if ( $('.content-drawer:visible').length ) {
       $('.tabs > li.active').removeClass('active');
    }
    return false;
});​


<ul class="tabs">
   <li class="focus">
       <a href="#" rel="#calc" class="tab"><i class="icon-plus"></i>Calculator</a>
   </li>
   <li>
       <a href="#" rel="#info" class="tab"><i class="icon-info"></i>Info</a>
    </li>
</ul>

<div class="content-drawer" id="calc">
    <p>Calc Content</p>    
</div>
<div class="content-drawer" id="info">
    <p>Info Content</p>    
</div>

Solution

  • Try this code

        $('.content-drawer').hide();
    
    $('.tab').click(function() {
        var $this = $(this);
        var target = $(this.rel);
        $this.closest('li').addClass('active focus');
        // Add the classes to the closest li of the clicked anchor
        $('.tab').not($this).closest('li').removeClass('active focus');
        // Remove the classes for the non-clicked items
        $('.content-drawer').not(target).slideUp();
        // Slideup the other contents
        target.delay(500).slideToggle();
        // Toggle the current content
        if (target.is(':visible')) {
            // Only if the target is visible remove the active class
            $this.closest('li').removeClass('active');
        } 
        return false;
    });​
    

    Check Fiddle