melkisadek
melkisadek

Reputation: 1053

Select accordion-toggle in nested collapse to fully close accordions

Using Twitter Bootstrap 2.3.2 Collapse plugin.

I'm having trouble trying to manipulate nested accordions with javascript.

I want to capture the id of the last clicked accordion-toggle so that I can refer back to it after I've closed all open accordions.

I can use the on shown/hidden events to globally close all open accordions but I need to then go back and open the last selected item (or do similar in another way if it is simpler).

I can't work out how to create a variable for the selected accordion-toggle. I can only access the accordion at the top level with the 'this' keyword.

Can I change the following so that it references the accordion-toggle?

$('.accordion').on('show', function () {
    var selected = this.**[Accordion-Toggle]**
    $('.accordion').on('hidden', function () {
        clearCollapse();
    });
  do something with selected item here...
});

----------UPDATE--------

After sorting out the event capture with Ammu's help, I was able to amend the clearCollapse function to do what I needed. The code actually selects the accordion-body rather than the accordion-toggle.

//function to fully collapse accordion on same page
function pageCollapse(inner) {
    $('#' + inner).find('.accordion-body').removeClass('in');
    $('#' + inner).find('.accordion-body').height('0px');
}    

//collapse inner accordion on same page
$('.accordion').on('hidden', function (e) {
    var selected = e.target.id;
    pageCollapse(selected);
});  

Upvotes: 1

Views: 788

Answers (1)

ammu
ammu

Reputation: 386

This may be a help for you . In your code make a little change

$('.accordion').on('show',function (event)){
var selected=event.target.id;          // give id of selected element
 $('.accordion').on('hidden',function () {
    clearCollapse();
 });
do something with selected item here... });

Upvotes: 1

Related Questions