Reputation: 633
I have a simple open close toggle box, fiddle here and wondered if it could be closed by just clicking anywhere else on the site (as well as its current button) (not necessarily another link) whitespace, anywhere etc..
$(document).ready(function() {
$('a.show_hide').click(function() {
$('.hidden-menu').toggle();
$(this).toggleClass('close');
});
});
Upvotes: 2
Views: 3044
Reputation: 7207
this is what you need: http://jsfiddle.net/5jzUD/9/
$(document).ready(function() {
$(document).on('click',function(clickPosition){
if (!$('.hidden-menu, a.show_hide').is(clickPosition.target) && $('.hidden-menu').has(clickPosition.target).length === 0){
$('.hidden-menu').hide();
$('a.show_hide').addClass('close');
}
else{
if($('a.show_hide').is(clickPosition.target) && $('.hidden-menu').css('display')!='none'){
$('.hidden-menu').hide();
$('a.show_hide').addClass('close');
return;
}
$('.hidden-menu').show();
$('a.show_hide').removeClass('close');
}
});
});
Upvotes: 1
Reputation: 20636
Use $(document).click()
to bind or capture a click event - anywhere else on the site.
Use event.stopPropagation()
in original a
click event. This would stop event bubbling.
And, don't use .toggle()
in the $(document).click()
function as it would also show()
the element.
Check this snippet.
$(document).ready(function () {
$('a.show_hide').click(function (event) {
event.stopPropagation();
$('.hidden-menu').toggle();
$(this).toggleClass('close');
});
$(document).click(function (e) {
$('.hidden-menu').hide();
$('a.show_hide').removeClass('close');
});
});
Instead of $(document)
you could also use : $('*:not(a.show_hide)')
: Demo
Upvotes: 1