Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: clicking nested elements

I have the following markup

<ol>
    <li class="ListItem">
        <span class="sub">@qItem.CategoryText</span>
        <input type="image" src="http://icons.iconarchive.com/icons/tatice/just-bins/256/bin-red-full-icon.png" width="30" class="deleteIcon" name="QuestionId" value="@qItem.Id" />
    </li>
</ol>

and the following script

$(".ListItem").click(function(){
doActionA();
});

$(".deleteIcon").click(function(){
doActionB();
});

When I click in image, it also triggers click of ListItem. I understand this is because image is inside ListItem. but I want ListItem's click not to be fired when image is clicked. Is there any way to do that ?

like image 398
Bilal Fazlani Avatar asked Jan 08 '13 06:01

Bilal Fazlani


2 Answers

$(".deleteIcon").click(function(e){
    doActionB();
    e.stopPropagation();
});
like image 149
Arvind Bhardwaj Avatar answered Nov 14 '22 03:11

Arvind Bhardwaj


You need to use event.stopPropagation() to prevents the event from bubbling up the DOM tree.

$(".deleteIcon").click(function(event){
    event.stopPropagation()
    doActionA();    
});

The event you binded with delete icon is firing the parent event binding with ListItem, so you need to stop propagation for parent event when child is source of event.

like image 5
Adil Avatar answered Nov 14 '22 04:11

Adil