Chip
Chip

Reputation: 653

How do I remove class from previous selection when clicking additional item?

http://jsfiddle.net/freqn/ZHt6V/2/

How do I remove class from previous selection when clicking additonal item in this accordion? I want the class to be removed from the previous clicked item when the next item is expanded. All other items should turn back to gray when new item is selected. Thank you.

(function () {

    $('dd').hide();
    $('dt').click(function(){
        $(this)
            .next()
            .slideToggle(200)
            .siblings('dd')
            .slideUp(200);
        });   

    $('dt').click(function(){
        $(this).toggleClass('active');

    }); 

})();

Upvotes: 0

Views: 813

Answers (1)

Uptown Apps
Uptown Apps

Reputation: 707

Edit: http://jsfiddle.net/uptownapps/ZHt6V/5/ -- Revision to add collapse functionality.

http://jsfiddle.net/uptownapps/ZHt6V/4/

First you can use the same click function to handle all of this. Also, I prefer to use removeClass and addClass rather than toggleClass just because I am able to keep track of what's happening in my head better that way.

    (function () {

    $('dt').click(function(){
        $(this) .next()
                .slideToggle(200)
                .siblings('dd')
                .slideUp(200);

        $('.active').removeClass('active');
        $(this).addClass('active');
    });

})();

You'll notice I also removed the $('dd').hide(); and instead added display: none; to the CSS definition for the dd element. This will fix the "flash" you see when the page loads before jQuery and your JS has run.

Upvotes: 1

Related Questions