Reputation: 543
I have a simple reveal panel appearing using toggleClass and toggling class 'active' to reveal panel. Once panel is revealed i'd also like the option to 'untoggle' and remove class 'active' to hide the panel by clicking anywhere on the body.
Here's my jQuery
$(".number-people .trigger").click(function(){
$(".number-people-popup").toggleClass("active");
});
I've tried doing
$("body").click(function(){
$(".number-people-popup").removeClass("active");
});
But it always clashes. I'm sure there's a simple way of doing this.
Here's a jsFiddle: https://jsfiddle.net/alexgomy/8r0Lkj2b/4/
Thanks
Upvotes: 0
Views: 109
Reputation: 5050
You're looking for stopPropagation() to stop event bubbling
Edit
Included <select>
within collapsed div
to reflect question on comments
$(".number-people .trigger").click(function(e) {
$(".number-people-popup").toggleClass("active");
e.stopPropagation();
});
$("body").click(function(e) {
if (!$(e.target).hasClass("number-people-popup") && $(e.target).parents(".number-people-popup").length === 0) {
$(".number-people-popup").removeClass("active");
}
});
.trigger {
cursor: pointer;
}
.number-people-popup {
display: none;
border: 1px solid #000;
padding: 30px;
width: 150px;
text-align: center;
}
.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="number-people">
<p class="trigger">
Click to trigger
</p>
</div>
<div class="number-people-popup">
Reveal panel here
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
</div>
<br><br><br><br><br> Once triggered i want to close by clicking anywhere in the background.
Upvotes: 1
Reputation: 139
Here's very quickly:
$('html').click(function() {
$(".number-people-popup").removeClass("active")
});
$(".number-people .trigger").on('click', function(e){
e.stopPropagation();
$(".number-people-popup").toggleClass("active");
});
.trigger{cursor:pointer;}
.number-people-popup{display:none;border:1px solid #000;padding:30px;width:150px;text-align:center;}
.active{display:block;}
<div class="number-people">
<p class="trigger">
Click to trigger
</p>
</div>
<div class="number-people-popup">
Reveal panel here
</div>
<br><br><br><br><br>
Once triggered i want to close by clicking anywhere in the background.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1