utdemir
utdemir

Reputation: 27236

Bootstrap Collapse - Jquery "Collapse all" function

I'm writing a personal feed reader using Bootstrap on frontend, and wanted to add a "Collapse/Expand All" button.

It's my first JavaScript/JQuery code, so I don't know how to debug it except printing variables in Firefox Developer Console.

My page structure consist of panels. User can expand or collapse a panel by clicking on panel header. And a button to collapse or expand all panels.

My solution works most of the times, but I noticed one odd behavior. Here is how I reproduce the problem:

  1. Open the page first time
  2. Expand one panel with clicking its header
  3. Now the collapse all button collapses the open panel, and expands the other ones. As if it "toggles" all panels instead of closing them.
  4. After this odd behavior, everything is normal, I can't reproduce the problem without refreshing the page. On every step open_panel_count variable looks normal.

Here is the methods I'm using:

$(function() {
  open_panel_count = 0;
  function update_toggle_button() { 
    $('#toggle-btn').text((open_panel_count ? "Collapse" : "Expand") + " All")
  }
  update_toggle_button(); // Run once on page load to text #toggle-btn

  $('#toggle-btn').click(function() {
    $('.panel-collapse').collapse(open_panel_count ? 'hide' : 'show');
  });

  $('.panel-collapse').on('shown.bs.collapse', function () {
    open_panel_count++;
    update_toggle_button();
  });

  $('.panel-collapse').on('hidden.bs.collapse', function () {
    open_panel_count--;
    update_toggle_button();
  });
});

Can anyone point me what I am doing wrong?

You can see the whole template in: https://github.com/utdemir/furby/blob/master/template.erb And access a demo at: http://p.cogunluklazararsiz.org/furby/

Upvotes: 8

Views: 71781

Answers (3)

JMP
JMP

Reputation: 567

$('.panel-collapse').collapse('hide');

Bootstrap/JQuery Collapse

Upvotes: 19

cbayram
cbayram

Reputation: 2259

According to the Twitter Bootstrap documentation, you can "activate your content as a collapsible element.", by running:

$('.panel-collapse').collapse({
  toggle: false
});

Adding this should resolve your issue. Give it a go.

$(function() {
  $('.panel-collapse').collapse({
    toggle: false
  });

...

http://getbootstrap.com/javascript/#collapse

Not sure why the twitter JS isn't picking up your data-target="#entry419294611" data-toggle="collapse". Tough to debug without a fiddle.

Upvotes: 9

Aguardientico
Aguardientico

Reputation: 7779

Try changing

  $('#toggle-btn').click(function() {
    $('.panel-collapse').collapse(open_panel_count ? 'hide' : 'show');
  });

For

  $('#toggle-btn').click(function() {
    var state = open_panel_count ? 'hide' : 'show';
    $('.panel-collapse').collapse(state);
  });

Upvotes: -2

Related Questions