views:

59

answers:

2

I have a menu that on .click triggers a slideToggle to show/hide elements of a list.

When the page first loads, all elements of the list are visible. As you click on the menu, which corresponds to the different elements in the list, different parts slide away. The menu looks like this:

One | Two | Three

The list looks like this:

<li class="one">Here's one thing</li>
<li class="two">Here's another thing</li>
<li class="three">Here's a third thing</li>

And what happens is when you click on ONE, two and three slide up, so you're only seeing the items with .one. That does happen. And when you click again on ONE, two and three slide down, so you're seeing everything again. That's exactly right.

However, things get weird, if you don't click back on ONE to expand the list, and instead jump to TWO: The expected action would be that you would now see items in the "two" class, without seeing .one and .three. Instead, you see ONLY .three clicking on THREE then shows you .one and .two and hides .three

That's a mess. Here's how I'm calling these right now:

$('#clickone').click(function(){
$('#result li:not(.one)').slideToggle();});

$('#clicktwo').click(function(){
$('#result li:not(.two)').slideToggle();});

$('#clickthree').click(function(){
$('#result li:not(.three)').slideToggle();});

There's got to be a method that simply works, right?

+1  A: 
var ooxx = {
    '#clickone' : '.one',
    '#clicktwo' : '.two',
    '#clickthree' : '.three'
},
$.each(ooxx, function(i, n) {
    $(i).click(function() {
        $(n).siblings().slideToggle();
    });
});

I guess something like this. Hope can help you:)

Xiezi
Hey cool, I didn't know about slideToggle(). I knew about toggle, and slideUp/Down, but not slideToggle. Thanks!
Unoti
+1  A: 
$('#clickone').click(function() {
    var li = $('#result li.one').slideDown().siblings();
    toggler(li);
});

$('#clicktwo').click(function() {
    var li = $('#result li.two').slideDown().siblings();
    toggler(li);
});

$('#clickthree').click(function() {
    var li = $('#result li.three').slideDown().siblings();
    toggler(li);
});

function toggler(el) {
    if (el.is(':visible')) el.slideUp();
    else el.slideDown();

}​
Reigel