Reputation: 800
As the title says, how to bind two selectors to open/close (add and remove class) on a div?
Simple HTML:
<div>
<a href="#" class="open">Open</a>
<div>
<span class="close">X</span>
</div>
</div>
Some jQuery:
$(function() {
var $open = $("a.open");
var $close = $("span.close");
$open.on("click", function() {
var $this = $(this);
if ($this.hasClass("active")) {
$this.removeClass("active");
$this.parent("div").removeClass("is-open");
} else {
$this.addClass("active");
$this.parent("div").addClass("is-open");
}
});
$close.on("click", function() {
// This and only this close should remove the active class from the div and remove the active class from "a".
});
});
Once again; if I click on "a" to open the div and then press "span" to close to div. Which is the best approach?
Upvotes: 0
Views: 47
Reputation: 74738
You can do this:
var $open = $("a.open");
var $close = $("span.close");
$open.on("click", function() {
var $this = $(this);
$this.addClass("active");
$this.parent("div").addClass("is-open");
});
$close.on("click", function() {
$(this).closest('.is-open').removeClass('is-open');
$(this).parent().prev().removeClass('active');
});
.is-open {
background: yellow;
border: solid 1px black;
}
.active {
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<a href="#" class="open">Open</a>
<div>
<span class="close">X</span>
</div>
</div>
Upvotes: 1
Reputation: 25537
You can use,
$close.on("click", function() {
var container = $(this).parent().parent();
container.find(".active").removeClass("active");
container.removeClass("is-open");
});
Upvotes: 1