Harrison
Harrison

Reputation: 2670

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.

Upvotes: 7

Views: 33775

Answers (5)

MatB
MatB

Reputation: 11

After trying many tomes I've ended with:

From source https://getbootstrap.com/docs/3.3/javascript/ .collapse hides content .collapsing is applied during transitions .collapse.in shows content

// Hide

if ($('#div').hasClass("in")) {$(#div).removeClass('in');}

// Show

$('#div').addClass('in');

Works for me!

Upvotes: 1

Dan Marshall
Dan Marshall

Reputation: 644

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

$thingToCollapse.collapse({ 'toggle': false }).collapse('hide');

Upvotes: 3

pasichnu4ka
pasichnu4ka

Reputation: 11

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

Upvotes: 0

Sherbrow
Sherbrow

Reputation: 17379

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

Upvotes: 16

Bizley
Bizley

Reputation: 18021

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');
    }
});

Upvotes: 1

Related Questions