简体   繁体   中英

Jquery click outside multiple div/elements

There are two sections targetDiv1 and targetDiv2 (not nested). And another section collapsibleDiv . I need to run a function(be it collapsing the div) on clicking outside the element targetDiv2 ; but the function should not be triggerred when clicking targetDiv1 . With the below code I'm unable to achieve this.. Any help would be great...

$(document).click(function(e) { 
    if(!$(e.target).closest('.targetDiv1').length && !$(e.target).is('.targetDiv1')) {
        $('.collapsibleDiv').slideDown();
    }
});

JSFiddle as per the answer from @Kweiss https://jsfiddle.net/vn8gmu8g/

You want the function to execute on a click outside Div1 or Div2, but your code only excludes Div1. Just add Div2 as well.

$(document).click(function(e) { 
    var $target = $(e.target);
    if(!$target.closest('.targetDiv1').length && !$target.hasClass('targetDiv1') && 
       !$target.closest('.targetDiv2').length && !$target.hasClass('targetDiv2')) {
        $('.collapsibleDiv').slideDown();
    }
});

Saving e.target in a variable and using hasClass() will make your code faster.

  $(".targetDiv2").click(function(){
           $('.collapsibleDiv').slideDown();
  })

It does what you want. It will collapse when you click div2 .

Try this : you have to add same if conditions for div2

$(document).click(function(e) {
    var $clickedElement = $(e.target); 
    if(!$clickedElement.closest('.targetDiv1').length && !$clickedElement.is('.targetDiv1') && !$clickedElement.closest('.targetDiv2').length && !$clickedElement.is('.targetDiv2')) {
        $('.collapsibleDiv').slideDown();
    }
});

I created a demo , and I would say, it is working...

$(document).click(function(e) { 
    if(!$(e.target).closest('.targetDiv1').length && !$(e.target).is('.targetDiv1')) {
        $('.collapsibleDiv').slideDown();
        alert("OK");
    }
});

If you click on targetDiv1 -> nothing happens

If you click on targetDiv2 -> alert

If you click anywhere else -> alert

I would say, this is what you described.

下面应该工作

$(document).click(function(e) { var target = $(e.target); if(!target.hasClass('.targetDiv1') && !target.hasClass('.targetDiv2')) { // perform you operation } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM