JQuery hiding div on click from outside
I would like to create a simple menu for each list item by clicking on it, but hide that div as soon as you click on it. Here's some simple code that will hopefully make sense.
$('.drillFolder').click(function(){
var id = $(this).attr('data-folder');
$(".drillDownFolder ul li > a").attr('data-id', id);
$(".drillDownFolder").show();
});
$("body").click(function(e){
if(e.target.className !== "drillDownFolder")
{
$(".drillDownFolder").hide();
}
});
//The hidden div
<div class="drillDownFolder" style="display:none">
<ul>
<li><a href="#" data-id="">Show Image</a></li>
<li><a href="#" data-id="">Edit Image</a></li>
</ul>
</div>
I know this is wrong, since the menu is displayed via .drillFolder links, clicking on the body immediately hides it. How can I avoid this.
Thanks if you can advise
+2
a source to share
2 answers
You can stop the click event from propagating from the .drillFolder callback using stopPropagation () .
$('.drillFolder').click(function(event){
event.stopPropagation();
var id = $(this).attr('data-folder');
$(".drillDownFolder ul li > a").attr('data-id', id);
$(".drillDownFolder").show();
});
$("body").click(function(e){
$(".drillDownFolder").hide();
});
+9
a source to share