lisovaccaro
lisovaccaro

Reputation: 34006

JQuery .click() selector ignore <a> child elements?

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?

Upvotes: 0

Views: 776

Answers (3)

Martin Seeler
Martin Seeler

Reputation: 6992

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

Upvotes: 2

Mister Epic
Mister Epic

Reputation: 16743

This is untested, but hopefully gives you the idea:

$(function(){
    $('div').click(function(e){
         if($(e.target).is('a')){
              e.stopPropagation();
         }
    });
});

Upvotes: 1

j08691
j08691

Reputation: 208022

You could use:

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

jsFiddle example

Upvotes: 2

Related Questions