jquery: get mouse click if inside a div or not
Solution 1
$("body > div").click(function() {
if ($(this).attr("id") == "in_or_out") {
// inside
} else {
// not inside
}
});
EDIT: just learned, that there is a negate:
$("body > div:not(#in_or_out)").click(function(e) {
// not inside
});
Solution 2
If you want to detect whether or not you've clicked inside or outside the div, set the event handler on the documentElement
and let it propagate from the other elements upwards:
$("html").click(function (e)
{
if (e.target == document.getElementById("in_or_out"))
alert("In");
else
alert("Out!");
});
Solution 3
Maybe this one will help you
$('body').click(function(){
//do smth
});
$('div#in_or_out').click(function(e){
e.stopPropagation();
// do smth else
});
Solution 4
Depends what you want. If you only want to execute code, when it was inside #in_or_out
, you can do:
$('#in_or_out').click(function(){ /* your code here */ });
You can have a status variable that says whether the mouse is in #in_or_out
or not:
var inside = false;
$('#in_or_out').hover(function() { inside = true; }, function() { inside = false; });
Then whenever a click occurs you can check with inside
whether the click was inside in_or_out
or not.
Reference: .hover()
Update:
No matter to which element you bind the click
handler, you can always do this:
$('element').click(function() {
if ($(this).attr('id') !== 'in_or_not') {
}
});
Solution 5
for inside it would be
$("#in_or_out").click(function() {
// do something here
});
for outside...I've got no idea.
Edit: You could try to do the same for body-tag (assigning a click-handler to the document itself). But I'm not sure if both events would fire by that.
trrrrrrm
Updated on August 12, 2020Comments
-
trrrrrrm over 3 years
i have this HTML page
<html> <body> <div>a</div> <div>b</div> <div>c</div> <div>d</div> <div id='in_or_out'>e</div> <div>f</div> </body> </html>
a,b,c,d,e and f could be divs also not just a plain text.
I want to get the mouse click event, but how could i know if it's inside or outside #in_or_out div ?
EDIT :: guys, i know how to check if the div is click or not, but i want my event to be fired when the click is outside that div
-
Andy E about 14 yearsJust remember
in
is a keyword in javascript and not allowed as a variable name ;-) -
Felix Kling about 14 years@Ande E: Yes, I noticed it, I changed it ;) Thanks anyways :)
-
Avi almost 7 yearsThis will not work if div (#in_or_out) contains other elements and the user clicks on inside element. Check this example jsfiddle.net/opd3ktdf/4
-
Andy E almost 7 years@avi, nope, neither will the accepted answer. For that you could do something like
.contains(e.target)
— jsfiddle.net/opd3ktdf/6 -
Avi almost 7 yearsYes, that will work, I was not showing the right answer in the Fiddle. Just explaining the use of your answered code.