user1038814
user1038814

Reputation: 9657

Prevent secondary click action in Jquery

I have a list and each item of the list has a div. If you click on the list item, I want it to do something (ex: alert("Clicked outside Div"); ), but I also want an action when I click on the div in the list (ex: alert("Clicked in Div");.

However, whilst the action is performed when I click the div, it also performs the action related to the click of the list item immediately after. Is it possible to prevent this behaviour so that only Clicked in Div is displayed?

<ul id="coll-selected-list" class="droptrue sort-drop">
       <li class="sortedli">
             <div class="sel-display-on" style="display: inline; float:left; width: 30px;">xx</div>
             Call Type
       </li>
</ul>

$('.sel-display-on').click(function () {
        alert("Clicked in Div");
    });
$('.sortedli').click(function () {
        alert("Clicked outside Div");
    });

Upvotes: 1

Views: 69

Answers (1)

j08691
j08691

Reputation: 207901

$('.sel-display-on').click(function (e) {
    e.stopPropagation();
    alert("Clicked in Div");
});

Your click event is bubbling up and triggering the click event on the list item when you click the div. Use e.stopPropagation(); to counteract this behavior.

jsFiddle example

Upvotes: 8

Related Questions