here - I want alert to happen when you click anywhere but not on the div.
When I click on div, alerts shows too.
JS
$("html, body").not('.entry-content').click(function() {
alert('d');
});
HTML
<div class="entry-content"> kkkk </div>
You can use the event argument to see what 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's still part of your html/body.. so you need to handle it inside the click function. Also you are just binding the click event..
So
// find html,body - not ones with class=entry-content - bind click
$("html, body").not('.entry-content')
So that doesn't prevent the alert as your div is still inside the body
As mentioned.. you only need to bind to the body really
$("body").click(function(e) {
if ($(e.target).hasClass('entry-content')) {
return false;
}
alert('d');
});
$("html *").click(function(e) {
if ( e.target.className.indexOf("entry-content") < 0 ) {
alert('d');
}
});
DEMO
The original code doesn't work because the .not()
applies to the selectors in front of it - html
and body
. Neither of them has the class of entry-content
, so the event fires
You can also stop propagation on the element clicked
$("body").click(function() {
alert();
});
$(".entry-content").click(function(e) {
e.stopPropagation();
});
Works also by clicking on a sub element
<div class="entry-content">Element
<span>Sub element</span>
</div>
Check out the Fiddle
The problem is that you're adding the click event to the HTML and BODY tags. So, first off you're going to get 2 alerts when you click in the body area. Also, because of the way events propagate up, clicking on the DIV in question will propagate the click event up to body and html as well. So, you need to do a check inside the click handler to determine whether or not you want to show the alert message.
I modified your jsfiddle below to only include HTML in your selector, and to check for the entry-content
class within 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 to 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.