tags:

views:

39

answers:

2

I have a sidebar menu that opens and closes hidden parts of the page through jQuery. The link both fades the hidden content and also adds and removes a class to the link. So for example the html / css

<ul>
<li><a class="linkOne" href="#">Link One</a></li>
<li><a class="linkTwo" href="#">Link Two</a></li>
</ul>

<div class="linkOneBox">Stuff</div>
<div class="linkTwoBox">Stuff</div>

<style type="text/css">
.linkOneBox,.linkTwoBox {display:none}
.current {background: #fff}
</style>

and the jQuery something like..

$('.linkOne').click(function() {
    $('.linkOneBox').fadeToggle();
    $(this).toggleClass('current'); 
    return false; 
    });

Anyways.. my question is, since i am using toggle, what is the best way to have all of the other toggles that were left open reset to off? How would I have it so that clicking a new link also hides all of the previously opened windows and removes the .current ?

+1  A: 

I'd make a few changes to the HTML first:

<ul id="menu">
    <li><a href="#b1">Link One</a></li>
    <li><a href="#b2">Link Two</a></li>
</ul>

<div class="box" id="b2">Stuff</div>
<div class="box" id="b1">Stuff</div>

Then:

$(document).ready(function(){

    // Initially hide the boxes
    $('.box').hide();

    $('#menu a').click(function(){

     $('#menu a').removeClass(); // Remove 'current' class from any links
     $('.box:visible').fadeToggle(); // Hide all previously visible boxes

     // Fade in the box where the id is the same as the href of the clicked link
     $($(this).attr('href')).fadeToggle(); 
     $(this).addClass('current'); // And highlight the menu link

     return false; 
    });

});

There is a bit of an overlap, so instead you might want to just hide() the open boxes before you fade the new one in.

Mark B
Yea! Thanks a lot.. that is so much more efficient than the path I was heading down. Regarding your comment on the overlap ... isnt that what you did? $('.box').hide(); To prevent the initial flicker I am tempted to just hide them in the css as they are visible while the scripts are loading and then I will have something else for people with js off.
zac
It does lose its toggle now as each link always turns it on.. i just added a close button for each window but if any ideas on how to keep the toggle functionality I would love to hear it :)
zac
Yes, all I did was to *initially* hide the boxes - if you changed the $('box:visible').fadeToggle(); to $('box:visible').hide() then I think this would look better. Also, if you move the initial $('.box').hide() into a cript block just after the .box divs then that should avoid the flicker and still leave them open for non-JS folks.
Mark B
+1  A: 

I agree with Mark, but use:

$(this).addClass('current');

Since toggleClass checks first if the class exists.

fredrik
thanks fredrik... you are right it does essentially make the toggle pointless
zac
Yep, good catch - I've edited my answer to take your suggestion into account.
Mark B