gopi1410
gopi1410

Reputation: 6625

jquery check if a div is clicked or not

I have the following html code:

<div id="gridStage">
   <div id="point1" class="point rounded-corners">
   </div>
</div>

#gridStage is a larger div inside which a smaller div #point is contained.

I want to call a correct function if a user clicks on #point and another wrong function if the user clicks anywhere on #gridStage but not on #point.

The problem is that when the user clicks on #point, jQuery also detects click on #gridStage as a result of which both the functions are called, which is not required.

Currently I am able to do it with the following code:

var pointClick=0;
$(".point").click(function() {
var pointClick=1;
    correct();
    setTimeout(function() {
       pointClick=0;
    },1000);
});
$("#gridStage").click(function() {
setTimeout(function() {
       if(pointClick===0) {
           wrong();
       }
    }, 500);
});

But I know this is an inefficient way, so is there any other good solution possible??

Note: All I want to do is that I have a grid as an image, then I overlay a div over it & I want to detect if a user has clicked a correct point or not for which I place a div on the correct point on top of the overlay grid, now I have to detect whether his click is on correct point or noyt. So if you have a better layout for this except the above which I am using, you are free to suggest so.

Upvotes: 3

Views: 7994

Answers (1)

h2ooooooo
h2ooooooo

Reputation: 39532

You need to stop the propagation.

$(".point").click(function(e) {
    correct();
    e.stopPropagation();
});
$("#gridStage").click(function() {
    wrong();
});

(note the e parameter on the line $(".point").click(function(e) { and the e.stopPropagation();)

Upvotes: 6

Related Questions