0

I need to fire an event when the user clicks on an element or anything inside it EXCEPT if he clicks on an <a> element.

This is what I'm trying now:

$( "div:not(a)" ).click(function(e) {
    alert("hello world");
});

You can better understand it here:

http://jsfiddle.net/cMBP3/1/

How can I do this?

j08691
  • 204,283
  • 31
  • 260
  • 272
lisovaccaro
  • 32,502
  • 98
  • 258
  • 410
  • 2
    possible duplicate of [Prevent execution of parent event handler](http://stackoverflow.com/questions/1398582/prevent-execution-of-parent-event-handler) – Felix Kling Aug 26 '13 at 20:31
  • 2
    FYI, the `div:not(a)` selector doesn't make a lot of sense. It means *"select every element with tag name `div` which has not tag name `a`*". Since an element cannot have two tag names, `div:not(a)` is equivalent to `div`. – Felix Kling Aug 26 '13 at 20:31
  • possible duplicate of [check element type clicked](http://stackoverflow.com/questions/17797038/check-element-type-clicked) – Chris Rockwell Aug 26 '13 at 20:38

3 Answers3

2

You could use:

$("div").click(function (e) {
    if (e.target.nodeName.toLowerCase() != 'a') alert("hello world");
});

jsFiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
2

Since your div is never an a, this won't work.

You have to check your target element for an a tag like this:

$('div').click(function(event) {
    var $target = $(event.target);
    if(!$target.is("a") ) {
      alert("hello world");
    }
});

I've updated your Fiddle: Have a look

Martin Seeler
  • 6,874
  • 3
  • 33
  • 45
1

This is untested, but hopefully gives you the idea:

$(function(){
    $('div').click(function(e){
         if($(e.target).is('a')){
              e.stopPropagation();
         }
    });
});
Mister Epic
  • 16,295
  • 13
  • 76
  • 147