开发者

jQuery hiding a div on click outside

I would like to build a simple menu for each list element clicked on but hide this div once you click outside it. Here is some simple code which hopefully will 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 whats wr开发者_如何学编程ong as the menu is show via the .drillFolder links the body click is then hiding it straight away. How can I avoid this.

Thank you if you can advise


You can stop the click event from propagating out of the .drillFolder callback with 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();
});


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

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

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜