John
John

Reputation: 1797

jQuery Show and Hide multiple divs with a selected class

I need to be able to show and hide divs based on which href class is 'selected' I have some code below:

http://jsfiddle.net/XwN2L/722/

I need to remove the 'all' option in the fiddle above.

So basically when a href has the class of selected the two links for the href are shown, then when a user clicks on another href, it hides the previous links and shows the new links with the class 'selected'

When they click on the link the selected class changes and the buttons hide and show accordingly?

Nearly there just need help on the last bits.

<div class="buttons">
 <a id="showall">All</a>
 <a class="showSingle" target="1">Div 1</a>
 <a class="showSingle selected" target="2">Div 2</a>
 <a class="showSingle" target="3">Div 3</a>
 <a class="showSingle" target="4">Div 4</a>
</div>

<div id="div1" class="targetDiv">
 <a href="#" class="button3">1a</a>
 <a href="#" class="button3">1b</a>
</div>

<div id="div2" class="targetDiv">
 <a href="#" class="button3">2a</a>
 <a href="#" class="button3">2b</a>
</div>

<div id="div3" class="targetDiv">
  <a href="#" class="button3">3a</a>
  <a href="#" class="button3">3b</a>
</div>

<div id="div4" class="targetDiv">popup COMPLETE</div>

<script>
 jQuery(function(){
    jQuery('.showSingle').click(function(){
          jQuery('.targetDiv').hide();
          jQuery('#div'+$(this).attr('target')).show();
     });
 });​
<script>

Cheers

Upvotes: 8

Views: 3437

Answers (1)

Ram
Ram

Reputation: 144689

You can use data-* attributes:

<div class="buttons">
  <a  id="showall" data-target="all" >All</a>
  <a  class="showSingle" data-target="1">Div 1</a>
  <a  class="showSingle selected" data-target="2">Div 2</a>
  <a  class="showSingle" data-target="3">Div 3</a>
  <a  class="showSingle" data-target="4">Div 4</a>
</div>

var $target = $('.targetDiv'); // caching object for better performance

$('.buttons a').click(function(e) {
    e.preventDefault();
    $(this).addClass('selected').siblings().removeClass('selected');
    var target = $(this).data('target');
    if (target === 'all') {
        $target.show();
    } else {
        $target.hide().filter('#div' + target).show();
    }
});

http://jsfiddle.net/fKHsB/

Upvotes: 4

Related Questions