user3097331 user3097331 - 9 days ago 4x
jQuery Question

jQuery Panel Will Not Toggle Active Class/Collapse One at a Time

I have two divs - one panel div that controls what shows on the other div. The problem is I have to apply a 'selected' class when a panel is active and also when the sub items under the panel is active as well. Right now, it does not "toggle" the selected class when active. This is what I have so far...


$('.options-display .options-list').hide();
$('#option-1').show(); // change to whatever is shown first on page
$('.collapse p').click(function(){
var target = '#' + $(this).data('target');



It is working as written, perhaps not as intended. There are two aspects which may not be obvious that led to your confusion.

First, this is a common typo that I have made as well, when using a class name in the toggle (or addClass or removeClass) make sure you do not include the . for the selector

$(this).toggleClass('selected');//should be this
//                   ^no `.`

To note: using this approach still leaves the original "selected" class intact. Perhaps you should preface this line of code with

$('.collapse .selected').removeClass('selected');

Second, the this binding in the click callback is going to be the element clicked, and in your example when selecting a sub item, it is the <p> element. Perhaps the selected class should be on the parent div in those cases if you are wanting to style the entire section. It was hard to tell as you left out the styling for the selected class.