ShaneKm
ShaneKm

Reputation: 21308

jquery click event ONLY when wrapped element clicked

I have the following html:

<ul class="treeList2">
<li class="topLevel marked checked"><div class="tlWrap clearfix"><input type="checkbox" checked="checked" class="checkbox"><strong>Level name here blah blah   <span>(3)</span></strong></div></li>

...

<script type="text/javascript">
/*<![CDATA[*/
    $(function(){           

        $('.treeList2 li.topLevel .tlWrap').click(function(){
            alert(this);
        });
    });
/*]]>*/
</script>

The problem is that this fires when I click the checkbox (which i don't want). I Only want to alert(this) when the 'div' is clicked (I do this so that I can change the div background). thanks

Upvotes: 1

Views: 965

Answers (4)

rahul
rahul

Reputation: 187020

You can check whether the element that triggered the event (e.target) has a class of tlWrap.

$(function(){
        $('.treeList2 li.topLevel .tlWrap').click(function(e){
            if($(e.target).hasClass("tlWrap")) {            
               alert(this);
            }
        });
});

See a working demo.

Upvotes: 0

naiquevin
naiquevin

Reputation: 7796

check if the target is not input element and then only alert.

$(function(){   
        $('.treeList2 li.topLevel .tlWrap').click(function(e){
            if (e.target.nodeName !== 'INPUT') {
                alert(this);
            }               
        });
});

Upvotes: 2

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

Looking at it, you need to call the parent?

$('.treeList2 li.topLevel .tlWrap').parent().click( ...

Although if you want to change the parent div when the checkbox is clicked:

$('.treeList2 li.topLevel .tlWrap').click(function(){
  $(this).parent().css('background-color','red');
});

[edit] Sorry, I mis-read the html. There's a 'not' function that you can exclude elements with:

$('.treeList2 li.topLevel .tlWrap').not('input').click( ...

This will fire when anything in the div is clicked on, except the checkbox.

Upvotes: 0

karim79
karim79

Reputation: 342625

You can prevent the click event on the checkbox from bubbling up to the parent like this:

$('.checkbox').click(function(e){
    e.stopPropagation();
});

You can try it here.

See http://api.jquery.com/event.stopPropagation/

Upvotes: 9

Related Questions