JQuery selector excluding elements and elements

I have a div used for filtering and I want it to close when something outside of the div is clicked. The selector I'm trying to create basically selects all the elements except a specific element and excludes its children. Here is what I tried but could not get the job

$('*:not(:has(.exclude *))').live('click', function() {HideFilter();}); 

simplified page structure:

 <div></div> <div> <div></div> <div> <div class="exclude"><inputs></div> </div> <div></div> </div> 

so I want all the divs, but one and all in .exclude to have an event. I was at it for a while, I need help.

+4
source share
2 answers

You tried

 $('*:not(.exclude, .exclude *)').live( ... ) 

? [And I see - the problem is that even if you exclude the material, the events are still bubbling.

Try something like this:

 $('*').live('click', function(e) { if (!$(e.target).is('.exclude, .exclude *')) // do interesting stuff } return false; }); 

This should stop the event from spreading to excluded things, without actually doing anything.

Example page: http://gutfullofbeer.net/balloon.html

change the update after 3 years: the .live() method is currently deprecated. The final example should look like this:

 $('body').on('click', '*', function(e) { if (!$(e.target).closest('.exclude').length) { // do interesting stuff } return false; }); 
+4
source

what about a slightly different strategy:

close all if nothing but click div:

 $("body").click(function(e){ if($(e.target).hasClass("exclude")){ //show stuff } else { //hide stuff } }); 

something like that

0
source

Source: https://habr.com/ru/post/1302171/


All Articles