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


isClicked = function($i, e){
  return $i.length>0 && $(e.target).parents().andSelf().index($i)>-1  ;
}

      

$ i is a jQuery object like $ ('# myDiv'), e is an event object



$(document).click(function(e) { 
    if( !isClicked( $('#myDiv') , e ) ) alert('not myDiv '); 
});

      

0


a source







All Articles