Reputation: 35
I have a menu that opens hidden divs using on click function. Id like to make them close when clicking outside of the toggled divs. I've tried few things but it renders a click function so it doesn't close hidden div when clicked again.
$(document).on('click', '.user-alt > li > a', function(e){
var popup = $(this).parent('li').find('.bar-pop');
$(".user-alt > li .bar-pop").not(popup).hide();
$('.menu-accountparent.selectedMenuItem').not($(this)).removeClass('selectedMenuItem');
$(this).toggleClass('selectedMenuItem');
popup.toggle();
});
Here is JSfiddle: http://jsfiddle.net/fkrosq8w/
I've tried these and works but like I said clicking on link in menu again does not close hidden box:
$('body').on('click', '*:not( .user-alt > li .bar-pop )', function() {
var popup = $('.user-alt > li .bar-pop');
popup.hide();
});
Upvotes: 0
Views: 1380
Reputation: 17755
Edit:
In light of your comment, it might be worth simplifying your markup and doing this in a more simple way. I'm not sure how much control you have over your markup, but maybe this will help:
Given this markup (I've added a class of toggle
to the anchor tags):
<ul class="user-alt">
<li class="messages">
<a title="Messages" class="toggle" href="#">Open/Close</a>
<div class="bar-pop">
Hidden block Here
</div>
</li>
<li class="messages">
<a title="Messages" class="toggle" href="#">Open/Close</a>
<div class="bar-pop">
Hidden block Here
</div>
</li>
<li class="messages">
<a title="Messages" class="toggle" href="#">Open/Close</a>
<div class="bar-pop">
Hidden block Here
</div>
</li>
</ul>
Hide div.bar-pop
by default:
.bar-pop{
display:none;
border:1px solid #ccc;
padding:10px;
}
Then toggle them backwards and forwards like so:
$('.toggle').on('click', function(e){
e.preventDefault();
$(this).next().toggle();
});
Then, listen for clicks on the document (or body if you wish), inspect the class name of the element where the click came from and react accordingly: if the class name matches toggle
or bar-pop
, do nothing, otherwise hide any visible popups.
$(document).on("click", function(e){
if(!e.target.className.match(/toggle|bar-pop/)){
$(".bar-pop").hide();
}
});
Here's an updated demo.
You can do it like so:
$(document).on("click", function(e){
if ($(".bar-pop").length && !e.target.className.match(/selectedMenuItem|bar-pop/)){
$(".selectedMenuItem").removeClass('selectedMenuItem');
$(".bar-pop").hide();
}
});
Upvotes: 0