ShahePars
ShahePars

Reputation: 135

how toggle all div tags

how? when click the .button, hide all .body div tags and show just closest .body tag div

my codes first one works, but when click the .button, show .body, but when click again, does't toggle ( show / hide ) that, any more?

How to do it properly?

Edit : how to change .button > span icon? ( positive or negative )

Edit : jQuery(this).find('positive').toggleClass('negative'); ?

Edit (saitho): JSFiddle: https://jsfiddle.net/nL4sxbj0/2/

HTML

<div class="box">

  <div class="header">

    <a href="#" class="button">

      <span class="positive"></span>

    </a>

  </div>

  <div class="body">

  </div>

</div>

CSS

.body {
  display:none;
}

.button .positive,
.button .negative {
  width:36px;
  height:36px;
  float:right;
  display:block;
  cursor:pointer;
}

.button .positive {
  background:url('../img/icon-del.png') no-repeat center center / 18px;
}

.button .negative {
  background:url('../img/icon-opn.png') no-repeat center center / 18px;
}

JQUERY

jQuery('.button').on('click' ,function(e) {

    e.preventDefault(); // Is this necessary? for <a href="#"></a>

    jQuery('.body').hide(); // Problem is hear i think

    jQuery(this).closest('.box').find('.body').toggle(); 

});

Picture

enter image description here

Upvotes: 0

Views: 742

Answers (2)

Saeed
Saeed

Reputation: 572

add class iconbtn to button span

<div class="box">

  <div class="header">

    <a href="#" class="button">

      <span class="iconbtn positive"></span>

    </a>

  </div>

  <div class="body">

  </div>

jQuery('.button').on('click' ,function(e) {
     e.preventDefault();

     var box = jQuery(this).closest('.box');

     var closestBody = box.find('.body');
     jQuery('.body').not(closestBody).hide(); // Hide all except above div

     jQuery(closestBody).toggle(); // if visible hide it else show it

     jQuery('.iconbtn').removeClass('negative').addClass('positive');     
     var iconBtn = box.find('.iconbtn');

     if (jQuery(closestBody).is(':visible')) {
       iconBtn.removeClass('positive').addClass('negative');
     } else {
       iconBtn.removeClass('negative').addClass('positive');
    }
});

jsFiddle Link

Upvotes: 2

Ignacy Kasperowicz
Ignacy Kasperowicz

Reputation: 421

The issue is that you have:

jQuery('.body').hide();

in your click callback, that means the body div is first being hidden and then toggle works as it should - it shows the div. There is no way it can hide it though, as before toggle you always first hide the div

Remove this line and it should work, check it here: JS Fiddle

Upvotes: 2

Related Questions