13

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 ?

5 Answers 5

24
$(".deleteIcon").click(function(e){
    doActionB();
    e.stopPropagation();
});
Sign up to request clarification or add additional context in comments.

Comments

5

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.

5 Comments

he wants to prevent click event of parent when clicked on child. Dont you think the event.stopPropagation() should be added on child's click?
The event binding will child will not trigger event for parent.
I think it does, look at this: jsfiddle.net/arvind07/WtxLC Try commenting the event.stopPropagation()
I could not see the code in jsFiddle there is something wrong ?
I have used stopPropagation on .deleteIcon. Can you explain why it worked? And if I remove it from there parent handler is also called.
1
$(document).on("click", ".deleteIcon", function() {
  doActionB();
});

This method is the only one I found to work with nested elements, especially those generated by a library such as Pivottable (https://github.com/nicolaskruchten/pivottable)

Comments

0
$(".deleteIcon").click(function(){
    doActionA();
    return false;  
});

Comments

0

Use .one(), as directed in the JQuery documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.