views:

71

answers:

1

I have 4 divs with content like below:

<div class="prodNav-Info-Panel">content</div>
<div class="prodNav-Usage-Panel">content</div>
<div class="prodNav-Guarantee-Panel">content</div>
<div class="prodNav-FAQ-Panel">content</div>

And a navigation list like this:

<div id="nav">
<ul id="navigation">
    <li><a class="prodNav-Info" ></a></li>
    <li><a class="prodNav-Usage" ></a></li>
    <li><a class="prodNav-Guarantee"></a></li>
    <li><a class="prodNav-FAQ" ></a></li>
    </ul>
</div>

When the page is first displayed I show all the content by executing this:

$('div.prodNav-Usage-Panel').fadeIn('slow');
$('div.prodNav-Guarantee-Panel').fadeIn('slow');
$('div.prodNav-FAQ-Panel').fadeIn('slow');
$('div.prodNav-Info-Panel').fadeIn('slow');

Now, when you click the navigation list item it reveals the clicked content and hides the others, like this:

    $('.prodNav-Info').click( function() {
        $('div.prodNav-Info-Panel').fadeIn('slow');
        $('div.prodNav-Usage-Panel').fadeOut('slow');
        $('div.prodNav-Guarantee-Panel').fadeOut('slow');
        $('div.prodNav-FAQ-Panel').fadeOut('slow');
    });

So what I have is 4 separate functions because I do not know which content is currently displayed. I know this is inefficient and can be done with a couple of lines of code. It seems like there is a way of saying: when this is clicked, hide the rest.

Can I do this with something like $(this) and $(not this)?

Thanks, Erik

+3  A: 

In your particular case you maybe able to use the .sibilings() method something like this:

$(this).fadeIn().sibilings().fadeOut()

Otherwise, lets say that you have a set of elements stored somewhere that points to all of your elements:

// contains 5 elements:
var $hiders = $(".prodNavPanel");

// somewhere later:
$hiders.not("#someElement").fadeOut();
$("#someElement").fadeIn();

Also, I would suggest changing the classes for your <div> and <a> to something more like:

<div class="prodNavPanel" id="panel-Info">content</div>
....
<a class="prodNavLink" href="#panel-Info">info</a>

This gives you a few advantages over your HTML. First: the links will have useful hrefs. Second: You can easily select all your <div>/<a> tags. Then you can do this with jQuery:

$(function() {
  var $panels = $(".prodNavPanel");
  $(".prodNavLink").click(function() {
     var m = this.href.match(/(#panel.*)$/);
     if (m) {
       var panelId = m[1];
       $panels.not(panelId).fadeOut();
       $(panelId).fadeIn();
       return false; // prevents browser from "moving" the page
     }
  });
});
gnarf
I have to study this but it looks really good...thanks for the quick response.
tg4FSI