I want to make a list of divs, like that:
<div class="a">
<div class="b"></div>
<div class="c"></div>
</div>
<div class="a">
<div class="b"></div>
<div class="c"></div>
</div>
<div class="a">
<div class="b"></div>
<div class="c"></div>
</div>
When you click on a div.b, div.c (only from the same div.a parent) should have a .vis class added. When you click on another div.b it adds the class to its sibling (div.c) and removes the class from the last clicked div.c. When don’t click div.b, but somewhere else, the .vis class is removed from every div.c.
window.onclick = function(window) {
if(window.target.className === 'b'){
$(".b").each(function() {
$(".b").on("click", function(){
$(this).siblings(".c").addClass("vis");
})
})
} else {
$(".c").removeClass("vis");
}
}
The code above doesn’t work as it should. I have to click 2 times to add the class (First it executes the function to check the target class and the second click adds the class).
When I click on another div.b the .vis class from the click before isn’t removed (so I have a few divs with .vis class, but I should have only 1 at a time).
How can I make this work?
3
Answers
You need something like this:
When
.b
is clicked, it will remove classvis
from all.c
, and add it to the.c
in connection to the clicked.b
Demo
Try this
https://jsfiddle.net/86ku05hp/