Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The hide method of Bootstrap collapse will show the collapse element

Here is a simple example: Link

  1. click the resize button, making the box div bigger
  2. click the button again, making it back to normal size. However, you will see the collapse element which should not be displayed.

I guess it's due to this line:

$("div.inbox").collapse("hide");


The purpose of this line is: if users clicked the a tag to show the collapse element, when they shrink the box div, the collapse element will be hidden.

The weird thing is the problem only happens at the first time of clicking resize button. I have no idea about why it happens.

like image 679
Harrison Avatar asked Jun 03 '14 11:06

Harrison


3 Answers

When you call the collapse plugin on an element, if it has not been initialized, the init process is triggered (see collapse.js source).

By default, the init process toggles the elements (showing it if it is hidden, and hiding it if it is visible) - equivalent to .collapse('toggle').

You'd need to initialize the collapsible element first, disabling the toggle-on-init parameter (see getbootstrap.com doc):

$("div.inbox").collapse({toggle: false});

See example on your updated fiddle

like image 97
Sherbrow Avatar answered Dec 09 '22 23:12

Sherbrow


In my scenario, I do want toggling after the initial hide. So I ended up using this:

$thingToCollapse.collapse({ 'toggle': false }).collapse('hide');
like image 26
Dan Marshall Avatar answered Dec 09 '22 23:12

Dan Marshall


It looks like collapse() fires for the first time with 'show' no matter what. Simple solution is to check if .inbox is shown and if so to fire collapse('hide'). We can get the state of the element by checking if class "in" is added - .collapse = element hidden, .collapse.in = element shown

$("button.resize").click(function(){
    var isExpanded = !$("div.box").hasClass("expanded");
    $("div.box").toggleClass("expanded", isExpanded);
    if ($("div.inbox").hasClass("in")) {
        $("div.inbox").collapse('hide');
    }
});
like image 36
Bizley Avatar answered Dec 09 '22 22:12

Bizley