JQuery $ ('html, body'). not ()

here - I want a warning to occur when you click anywhere but not on a div.

When I click on the div, warnings appear.

Js

$("html, body").not('.entry-content').click(function() { alert('d'); }); ​ 

HTML

 <div class="entry-content"> kkkk </div>​ 
+4
source share
4 answers

You can use the event argument to see which target was clicked and return false

 $("html, body").click(function(e) { if ($(e.target).hasClass('entry-content')) { return false; } alert('d'); });​ 

http://jsfiddle.net/keyZw/

You are using the .not () filter, but it is still part of your html / body .., so you need to handle it inside the click function. Also you just bind the click event.

So,

  // find html,body - not ones with class=entry-content - bind click $("html, body").not('.entry-content') 

Thus, this does not prevent the warning, since your div is still inside the body.

As mentioned, you only need to get attached to the body really

 $("body").click(function(e) { if ($(e.target).hasClass('entry-content')) { return false; } alert('d'); });​ 
+17
source
 $("html *").click(function(e) { if ( e.target.className.indexOf("entry-content") < 0 ) { alert('d'); } }); 

Demo


The source code does not work because .not() is applied to the selectors in front of it - html and body . None of them have an entry-content class, so the event fires

+6
source

You can also stop the spread on the item by clicking

 $("body").click(function() { alert(); }); $(".entry-content").click(function(e) { e.stopPropagation(); }); 

It also works by clicking on an additional element.

 <div class="entry-content">Element <span>Sub element</span> </div>​ 

Take a look at fiddle

+1
source

The problem is that you are adding the click event to the HTML and BODY tags. So, first you will get 2 warnings when pressed in the body area. In addition, because events are being distributed, clicking on the DIV in question will propagate the click event to body and html. So, you need to check inside the click handler to determine if you want to show a warning message.

I modified your jsfiddle below to include only HTML in your selector, and check the entry-content class inside the handler.

http://jsfiddle.net/m2eqS/6/

 $("html").click(function(e) { if(!$(e.target).hasClass("entry-content")){ alert('TEST'); } }); ​ 

The difference between binding to HTML and BODY is that if you want to be able to click anywhere on the page below where the content / body ends, you should use HTML. Otherwise use BODY.

0
source

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


All Articles