简体   繁体   中英

Close current toggle div when clicked onto another div

So right now, I have a basic slide and toggle script which with help now has a background added to it when clicked. However, I would like it so when another "CLICK ME" is clicked it closes that div and opens the new div. In essence I don't want toggled divs constantly overlapping each other.

http://jsfiddle.net/schermerb/rAMQT/6/

<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>
<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>
<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>
<div class="toggleBtn">CLICK ME</div>
<div class="below">OH NO IM HIDDEN</div>

.toggleBtn {
    font:14px noral Futura, sans-serif;
    color:black;
    margin:50px;
    cursor:pointer
}
.below {
    background:red;
}
.toggleBtn.active{
    background:blue;   
}

    $(document).ready(function () {
        var content = $('.below').hide();
        $('.toggleBtn').on('click', function () {
            $(this).next('.below').slideToggle();

            $(this).toggleClass('active');
            return false;
        });
        //register the handler to button element inside .below
        $('.below .close').on('click', function () {
            //find the ancestor .below element of the clicked button
            $(this).closest('.below').slideToggle();
        });
    });

Try this way:

       var $this = $(this);
       $this.next('.below').slideToggle().siblings('.below').slideUp();
       $this.toggleClass('active').siblings('.toggleBtn.active').removeClass('active');

instead of

     $(this).next('.below').slideToggle();

Fiddle

Use this:

var the_others = $('.active').not(this);
the_others.removeClass('active');
the_others.next('.below').slideUp();

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM