How can I toggle all other divs using addClass removeClass?

I'm trying to customise an existing bit of jQuery code for toggled content to allow me to close all other divs than the one I have clicked.

The code:

$('.et_lb_toggle_title').click(function(){
        var $this_heading = $(this),
            $module = $this_heading.closest('.et_lb_toggle'),
            $content = $module.find('.et_lb_toggle_content');

        $content.slideToggle(700);

        if ( $module.hasClass('et_lb_toggle_close') ){
            $module.removeClass('et_lb_toggle_close').addClass('et_lb_toggle_open');
        } else {
            $module.removeClass('et_lb_toggle_open').addClass('et_lb_toggle_close');
        }
    });

Currently this allows more than one div to be opened. What I'd like to achieve is when you open one div, all others close.

I think I need to target all other divs using

$('.et_lb_toggle_title').not($(this))

I've been struggling with it for a while and now my head is spinning!

Here's a jfiddle if it helps. NB (The divs are usually closed by default).

Any help, as always would be hugely appreciated!

Answers


Try

var $contents = $('.et_lb_toggle_content').hide();
var $modules = $('.et_lb_toggle').addClass('et_lb_toggle_close');
$('.et_lb_toggle_title').click(function(){
    var $this_heading = $(this),
        $module = $this_heading.closest('.et_lb_toggle'),
        $content = $module.find('.et_lb_toggle_content');

    $content.stop(true, true).slideToggle(700);
    $contents.not($content).stop(true, true).slideUp();

    $module.toggleClass('et_lb_toggle_open et_lb_toggle_close');
    $modules.not($module).removeClass('et_lb_toggle_open').addClass('et_lb_toggle_close');
});

Demo: Fiddle


Need Your Help

Trouble porting over python-2.7 curses to python-2.4

python ncurses curses python-2.4

I wrote my python code at home for 2.7, but now I'm trying to fix it to run on 2.4 here at work.

Rails 3 Cocoon link_to_add_association Renders Partial Twice

ruby-on-rails-3 nested-attributes cocoon-gem

My partial gets rendered twice instead of only once, as expected. Any thoughts?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.