2

I've got an element inside a div which has a click event associated to it. Both click events work fine, except they both fire at the same time.

When I click on the inner element to disable the parent div's click event:

My html (inside a @foreach MVC Razor loop):

<td class="tdfuncLangSignOff tdNotChecked tdLang@(item.Language.Name)" title="@(item.SignedOffStatus)">
    <div class="addComment"></div>
    @Html.Hidden("funcSignOffId", item.Id)
</td>

My jquery:

var handler = function () {
    var thisTD = $(this);
    var signOffId = thisTD.parent().children("input#funcSignOffId").val();
    console.log("parent div click");
}

    $(".tdfuncLangSignOff").click(handler);

$(".addComment").click(function () { 
    $(this).parent().unbind("click")
    console.log("nested div click");
    //$(this).parent().click(handler)
});

I found the handler idea from this thread

This allows me to click on the addComment div and disable the click on the parent div as I wanted. But the rebinding obviously doesn't happen. When I uncomment $(this).parent().click(handler) in the addComment click function the click triggers and the console displays "parent div click".

How can I rebind the click of the parent div without having it triggered immediately?

Community
  • 1
  • 1
LanFeusT
  • 2,392
  • 5
  • 38
  • 53

3 Answers3

5

If I understand you properly: In order to stop propagation of the event, use event.stopPropagation().

example:

<div id="a">
    Outer
    <div id="b">Inner</div>
<div>

and in JQuery:

$("#a").click(function(event) {alert("a");});
$("#b").click(function(event) {alert("b"); event.stopPropagation();});

You can read more here: http://api.jquery.com/event.stopPropagation/

Naor
  • 23,465
  • 48
  • 152
  • 268
  • Doh... I've used that stopPropagation on many other functions that had a "live" event, didn't even think of using it here. Thanks that worked! – LanFeusT Aug 09 '11 at 00:00
0

You can try:

$(this).parent().bind('click');
Perception
  • 79,279
  • 19
  • 185
  • 195
Rafay
  • 30,950
  • 5
  • 68
  • 101
  • That doesn't work. When you unbind you lose everything you've setup on the element. That's why I had the `click(handler)` – LanFeusT Aug 08 '11 at 23:59
0

I suspect the reason is because you are rebinding the click handler in the child click event, and THEN the event propagates to the next level (its parent), which now has the click handler again.

Unless I'm missing something else, Naor's advice with stopping propagation should serve your purpose.

zdyn
  • 2,155
  • 1
  • 15
  • 17
  • Yup, that made the trick :) Although I didn't think the event would propagate after unbinding and rebinding. – LanFeusT Aug 09 '11 at 00:17