Ray
Ray

Reputation: 171

Toggle class on multiple items

I need to toggle the 'bg' class on an opened menu item. It works fine if they're activated and deactivated one at a time. But when one is opened when another is already activated, then the class isn't added/removed properly. Cheers.

http://jsfiddle.net/6a3eZ/31/

jQuery(document).ready(function(){                  
    jQuery('.menu ul').hide();
    jQuery('.menu li.sub').click(function() {
        jQuery(this).find('a:first').toggleClass('bg');
        jQuery(this).find('ul:first').toggle(0)
               .end().siblings('li').find('ul').hide(0);
    });
});

Upvotes: 0

Views: 303

Answers (1)

Joe
Joe

Reputation: 15558

Here's a working version: http://jsfiddle.net/6a3eZ/39/

It uses this code:

jQuery('.menu li.sub').click(function () {
    var target = jQuery(this).children('a');

    if(target.hasClass('bg')){
        target.removeClass('bg');
    }else{
        jQuery('.menu-item > a').removeClass('bg');
        target.addClass('bg');
    }

    jQuery(this).find('ul:first')
                .toggle(0)
                .end()
                .siblings('li')
                .find('ul')
                .hide();
});

Upvotes: 3

Related Questions