middleendian middleendian - 3 months ago 7
HTML Question

Toggle state of multiple elements by clicking one of them

I have following structure on a page:

<div class="mycontainer">
<div class="mysubclass">
<div class="myheader">header 1</div>
<div class="mycontent">content 1</div>
</div>
<div class="mysubclass">
<div class="myheader">header 2</div>
<div class="mycontent">content 2</div>
</div>
<div class="mysubclass">
<div class="myheader">header 3</div>
<div class="mycontent">content 3</div>
</div>
</div>


I need to get the following behaviour:
Right after page load all of them are closed. When I click on the first mysubclass, its myheader and mycontent should get additional class active. When I click on it again it should be removed. All the other elements shouldn't become an active class.
When I klick on first mysubclass, its myheader and mycontent should get additional class active again. When I click a second mysubclass, the active classes should be removed from the first mysubclass and added to the elements of the second (clicked) mysubclass.

In fact I need to simulate opening and closing elements with content, so when it's closed, content is not visible, and when I cklick on an element it gets class active and content is shown.

My JQuery code is following:

$(".mysubclass").click(function(e) {

if ($(".myheader").hasClass("activ") && $(".mycontent").hasClass("activ")) {
$(".myheader").removeClass("activ");
$(".mycontent").removeClass("activ");
} else {
$(".myheader").siblings().removeClass("active");
$(".mycontent").siblings().removeClass("active");
$(".myheader").addClass("active");
$(".mycontent").addClass("active");
}
});


How can I get this behaviour working without changing html code?
Here is my example of this problem: JSFiddle example .

Answer

This should work

 $(".mysubclass").click(function(e) { 
   if ($(this).find(".myheader").hasClass("active") && $(this).find(".mycontent").hasClass("active")) {

    $(this).find(".myheader").removeClass("active");
    $(this).find(".mycontent").removeClass("active");
} else {
    $(".mycontainer .active").removeClass("active");
    $(this).find(".myheader").addClass("active");
    $(this).find(".mycontent").addClass("active");
  }
});

https://jsfiddle.net/po3Lj3rm/13/