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