mrfr
mrfr

Reputation: 1794

How to hide a collapsed element if another one is shown

I have 3 buttons which when clicked collapses and a form is shown. What I want is if one is already collapsed then I want it to hide again if another one is clicked.

My fiddle: https://jsfiddle.net/77soggnv/

This is my js code:

$(document).ready(function(){

    //See which panel has been clicked
    $("#citizen").click(function(){
        $(this).data('clicked', true);
    });
    $("#organisation").click(function(){
        $(this).data('clicked', true);
    });
    $("#anonymous").click(function(){
        $(this).data('clicked', true);
    });

    //Hide the other panels if one is clicked
    if($("#citizen").data('clicked')){
        $("#organisation").collapse("hide");
        $("#anonymous").collapse("hide");
    }
    if($("#organisation").data('clicked')){
        $("#citizen").collapse("hide");
        $("#anonymous").collapse("hide");
    }
    if($("#anonymous").data('clicked')){
        $("#organisation").collapse("hide");
        $("#citizen").collapse("hide");
    }    

});

Upvotes: 0

Views: 1579

Answers (2)

Shady Alset
Shady Alset

Reputation: 5714

Simply you can do it like:

$(".btn").click(function(){
    $('.collapse.in').collapse('hide');
});

Updated Fiddle

Upvotes: 6

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

Since the clicking elements have common classnames and structure, we don't have to attach event separately.

$(".btn.btn-primary").click(function() {
  var next = $(this).next();
  $(".collapse").not(next).slideUp();
  next.slideToggle();
});

Fiddle

next() method will return the element after the current element.

Upvotes: 0

Related Questions