Reputation: 21
when i click .foo
area , .bar
will show.
when i click document
area , .bar
will hide.
But i don't know how to do when i click .foo
area to make .bar
hide.
<div class="foo"></div>
<div class="bar"></div>
I have read this question this article, so i don't want to use event.stopPropagation()
in my code because it is dangerous.
$('.foo').click(function() {
$('.bar').show()
})
$(document).mouseup(function(e) {
var _con = $('.bar');
if (!_con.is(e.target) && _con.has(e.target).length === 0) {
$('.bar').hide();
}
});
.foo {
width: 100px;
height: 100px;
background: red;
margin-bottom: 20px;
}
.bar {
width: 100px;
height: 100px;
background: green;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="foo"></div>
<div class="bar"></div>
Upvotes: 2
Views: 621
Reputation: 1368
You can do this by 2 way, if the first approach is not working the second might work. Please have a look and test.
$('.foo').click(function(){
$('.bar').toggle();
});
//2nd approach
$('.foo').click(function(){
var bar = $('.bar');
if(bar.css('display') == "block"){
bar.css('display', 'none');
}else{
bar.css('display', 'block');
}
});
Upvotes: 4