photocurio
photocurio

Reputation: 156

JQuery accordion won't bring back default panel

This is not a jQuery UI accordion, just a show/hide script. It is a list of links that are supposed to toggle divs with corresponding anchors.

My problem is that the first link and initial div, which displays by default, won't come back after it has been hidden. This is my javascript:

$('.active').click(function() {
    return false;
});
$('.ready').click(function() { 
    var accordionid = $(this).attr("href");

    // links are either 'active' or 'ready' 
    $('.active').removeClass('active').addClass('ready');
    $(this).removeClass('ready').addClass('active');

    // panels are have class 'showing' if they display
    $('.showing').slideToggle().removeClass('showing');
    $(accordionid).slideToggle().addClass('showing');  
    return false;
});

I have a fiddle here that shows my problem: http://jsfiddle.net/g0e00L2p/

I'd expect this script to only fire on links that have the 'ready' class. But for some reason it also fires on links that have the 'active' class.

Upvotes: 0

Views: 49

Answers (2)

isherwood
isherwood

Reputation: 61083

Since you weren't using event delegation to monitor changes to the DOM (commonly done via the on() method), jQuery only knew of your elements as it saw them on initial page load. It wasn't aware that the classes had changed from the perspective of the click function, which is a static object.

All that class toggling can be eliminated. jQuery does that for you.

$('#accordion li a').click(function (e) {
    var accordionid = $(this).attr("href");

    $('.resume-content').not(accordionid).slideUp();
    $(accordionid).slideDown();

    e.preventDefault();
});

Demo

Note that I added an overflow statement to the CSS to eliminate the slide jump.

Upvotes: 2

Phil Tune
Phil Tune

Reputation: 3325

You only have jQuery checking for .ready instead of checking all of the links. So I would do this:

HTML

Add class tabs_list to the <ul>:

<ul class="tabs_list"> 
    <li><a href="#biography" class="active">biography</a></li>
    <li><a href="#activities" class="ready">Professional Activities</a></li> 
    <li><a href="#admissions" class="ready">Bar Associations</a></li> 
</ul>

jQuery

And check all <a> descendents of .tabs_list. When .ready is clicked, make sure everyone turns .ready, not just anyone who is .active, but then make $(this) .active. Make sense?

$('.tabs_list a').click(function(){
    if($(this).hasClass('ready')) {
        $('.tabs_list a').removeClass('active').addClass('ready');
        $(this).removeClass('ready').addClass('active');

        var accordionid = $(this).attr("href");
        $('.showing').slideToggle().removeClass('showing');
        $(accordionid).slideToggle().addClass('showing')
    }
    return false;
});

Updated jsFiddle

Upvotes: 1

Related Questions