views:

765

answers:

6

Hello

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

+1  A: 

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.

Bobby
+1  A: 

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') {

     }
 });
Felix Kling
Just remember `in` is a keyword in javascript and not allowed as a variable name ;-)
Andy E
@Ande E: Yes, I noticed it, I changed it ;) Thanks anyways :)
Felix Kling
A: 

Like this?

$("#in_or_out").click(function() {
    alert("IN DIV!");
});
dale
+7  A: 
$("body > div").click(function() {
    if ($(this).attr("id") == "in_or_out") {
        // inside
    } else {
        // not inside
    }
});
harpax
+1 for binding only to div elements.
karim79
+3  A: 

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!");
});
Andy E
+1 for `e.target`
karim79
thank you, sir!
Andy E
A: 

Maybe this one will help you

$('body').click(function(){
    //do smth
});
$('div#in_or_out').click(function(e){
    e.stopPropagation();
    // do smth else
});
Ionut Staicu