Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide, Show, HIDE/SHOWALL buttons

Tags:

jquery

Heres the code: http://jsfiddle.net/t2nite/KCY8g/

I was creating these hiding boxes using jquery.

Each box has some text and a "SHOW" and "HIDE" button. I'm trying to create a "SHOW/HIDE all" button.

But when I tried the code at the bottom the whole button disappears.

$("#btn").toggle(function() {
   $(".para2, .para3, .para4").hide(200);
   $(".para2, .para3, .para4").show(200);
});

This is the closest I can get to what I want.

$("#btn").click(function() {
   $(".para2, .para3, .para4").toggle(200);
});

The code on top works, but instead of hiding or showing all the boxes it just toggles them between hide and show. Help.

I only want the contents hidden and the buttons are not inside the para classes.

like image 344
t2nite Avatar asked Oct 15 '12 20:10

t2nite


1 Answers

You need to loop through each element to check whether they are hidden or not. It really depends on whether you want to first hide them all or show them all. Here is what you need:

// To toggle each element's state
$("#btn").click(function() {
   $(".para2, .para3, .para4").each(function (index, element) {
       if ($(this).is(':visible')) {
           $(this).hide(200);
       } else {
           $(this).show(200);
       }
   });
});

// To show all and hide all afterwards or vice-versa (change the attr check)
$("#btn").click(function() {
   if ($(this).attr('data-show')) {
       $(".para2, .para3, .para4").show(200);
       $(this).attr('data-show', false);
   } else {
       $(".para2, .para3, .para4").hide(200);
       $(this).attr('data-show', true);
   }
});

// To hide all if one is shown
$("#btn").click(function() {
   var oneShown = false;
   $(".para2, .para3, .para4").each(function (index, element) {
       if ($(this).is(':visible')) {
           oneShown = true;
       }
   });
   if (oneShown) {
       $(".para2, .para3, .para4").hide(200);
   } else {
       $(".para2, .para3, .para4").show(200);
   }
});
like image 171
Konstantin Dinev Avatar answered Sep 27 '22 20:09

Konstantin Dinev