tags:

views:

37

answers:

2

I have a div, containing text and a few links. I want to trigger an onclick event, only if the click occurs anywhere in the div, but not on any of the links.

What would be the best way (performance wise) to implement this using jQuery?

The one I use is

$('#div').click(function(){

});

but it disables all the #div > a

+3  A: 

You can use the :not() Selector

$("#div :not(a)").click(function(){
});

This will bind click to all elements inside the div which are not <a> tags.

$("#div").click(function(e){
    if (e.target.tagName === "A")
    {
        return false;
    }
    else
    {
        alert("click");
    }
});

This will bind a click handler to div itself and then check for the target and if it is not <a> then alert will be shown.

rahul
i don't think that works. http://jsfiddle.net/ayM7R/
Anurag
Its because your selector is wrong. You have written `$("#div:not(a)")` instead of `$("#div :not(a)")`
rahul
See this in action. http://jsfiddle.net/RmQQC/
rahul
`#div :not(a)` will trigger the click handler for all non `<a>` descendants, but *not on clicking anywhere in the div itself* as the question says.
Anurag
The 2nd one worked! Thanks a lot guys!
Anant
+2  A: 
$('#div').bind('click', function(e){
   if(e.target == this){
        // do something
   }
});

Kind Regards

--Andy

jAndy
Will this work for other elements inside the div?
rahul