Reputation: 5067
I have a div .post-control
with an onClick event. After clicking, an inner div .post-control-popover
appears. After a second click, the inner div disappears. The code I am using :
$('.post-control').click(function(e){
$(this).toggleClass("active");
var bool = $('.post-control').hasClass('active');
if(bool)
{
$('.post-control-popover').show();
}
else
{
$('.post-control-popover').hide();
}
e.preventDefault();
});
What should I add to this code so that, an onClick outside the outer div will make the inner div disappear.
Upvotes: 0
Views: 277
Reputation: 5067
Or this:
$('.post-control').click(function(e){
$(this).toggleClass("active");
var if_post_control_active = $('.post-control').hasClass('active');
if(if_post_control_active)
{
$('.post-control-popover').show();
$(document).click(function() {
$('.post-control-popover').hide();
});
}
else
{
$('.post-control-popover').hide();
}
e.preventDefault();
e.stopPropagation();
});
Upvotes: 0
Reputation: 1586
you can solve it easily in a more simple way.
$('.post-control').click(function(e){
$('.post-control-popover').toggleClass('disable');
});
you now just have to add to your css a class called 'disable' and give it either display:none, opacity:0 or visibility: hidden.
greetings Timotheus
Upvotes: 0
Reputation: 4177
$('.post-control').click(function(e){
$('.post-control-popover').show();
});
$('body').click(function(e){
e.preventDefault();
if(e.currentTarget.class != 'post-control-popover') {
$('.post-control-popover').hide();
}
})
Upvotes: 1
Reputation: 388316
Try
var $pc = $('.post-control'),
$pcp = $('.post-control-popover');
$pc.click(function (e) {
$(this).toggleClass("active");
$pcp.toggle($(this).hasClass('active'));
$(document).one('click', function () {
$pc.removeClass("active");
$pcp.hide()
})
return false;
});
Demo: Fiddle
Upvotes: 2
Reputation: 10148
You can add a single event for the whole document that closes your .post-control-popover
$('.post-control').click(function(e){
$(this).toggleClass("active");
var bool = $('.post-control').hasClass('active');
if(bool)
{
$('.post-control-popover').show();
$(document).one('click', function() {
$('.post-control-popover').hide();
});
}
else
{
$('.post-control-popover').hide();
}
e.preventDefault();
});
one
method binds a listener to an event and destroys it after one fire.
Upvotes: 1