0

I am attempting a one page design using loads of jQuery. I have a few main navigation elements and depending on which is clicked, different divs are shown or hidden. For example the html:

<div class="box a">
    <div class="inner">
        <a class="boxLink circle black" href="#">Link a</a>
    </div>
</div>
<div class="box a1 hidden">
    <div class="inner circle">
        <a class="boxLink" href="#">a1</a>
    </div>
</div>
<div class="box a2 hidden">
    <p class="green">a2</p>
</div>
<div class="box b">
    <div class="inner">
        <a class="boxLink circle black" href="#">Link b</a>
    </div>
</div>
<div class="box b1 hidden">
    <div class="inner circle">
        <a class="boxLink" href="#">b1</a>
    </div>
</div>
<div class="box b2 hidden">
    <p class="green">b2</p>
</div>

and the jQuery

$(".a").click(function(){
    $('.b').hide();
    $('.b1').hide();
    $('.b2').hide();
    $('.a1').slideDown({
        duration:500,
        complete:function(){
            $('.a2').slideDown('1000');
        }
    });
    return false
});

$(".b").click(function(){
    $('.a').hide();
    $('.a1').hide();
    $('.a2').hide();
    $('.b1').slideDown({
        duration:500,
        complete:function(){
            $('.b2').slideDown('1000');
        }
    });
    return false
});

What is a better, more efficient way to write this and check if unwanted divs are visible? I did read this solution but I am hoping to keep this as div blocks and not as a list.

Community
  • 1
  • 1
Zac
  • 12,637
  • 21
  • 74
  • 122

3 Answers3

9

.is(':visible') for very simple checking. returns a boolean.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • thanks, is that even necessary though? or would it be the same as me just saying .hide even if they are already hidden? – Zac Jul 23 '10 at 04:52
1

You can call hide and show methods even on elements that are already in the desired state.

$('#abc').hide() will hide #abc if not hidden, and do nothing if it is

Same goes for .show().

So I suppose there is no need for Sanity Check for already hidden elements

Om Shankar
  • 7,989
  • 4
  • 34
  • 54
-1

well you can do all the hiding in one statement, like:

$('.b, .b1, b2').hide();

other than that, i'm not sure i see why you need to check visibility? You can hide already hidden elements w/o issue

I'd also do the sliding more concisely like:

$('.a1').slideDown(500, function() {
     $('.a2').slideDown(1000);
});
Scott Evernden
  • 39,136
  • 15
  • 78
  • 84