Manoj Amalraj
Manoj Amalraj

Reputation: 575

How to selectively unbind a delegated event on an element?

Consider the following code:

    <div class="parent1">
      <div class="child">child1</div>
    </div>
    <div class="parent2">
      <div class="child">child2</div>
    </div>

If a mouseenter event is bounded to .child as

   $(document).on("mouseover mouseout", ".child", function(){ ..}

how to unbind this for .parent2.child alone, but still have it binded for .parent1.child ?

Upvotes: 1

Views: 31

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34178

I believe you should use the document since that is where this is bound, then find those children and do off()

$(document).find(".parent2").off("mouseover mouseout", ".child");

I tested using revised markup, making the assumption that you simply did not properly close your div with the

<div class="parent1">
      <div class="child">child1</div>
<div>...

I used this markup to test (divs are peer/siblings rather than grand child). Clarify if that is NOT a correct assumption by posting correct markup.

<div class="parent1">
  <div class="child">child1</div>
</div>
<div class="parent2">
  <div class="child">child2</div>
</div>

Turns out that after testing the first attempt did NOT work. This is because the event binds to the document, then filters by the children with the class .child selector, firing when it has a proper element. I was unable to change that "filter" on those bindings so I had to simply "redo" the binding, filtering on the new children - which will NOT properly work IF you add new elements AFTER this - you will need to execute this IF you subsequently re-add more children - notice it binds to the .child not document. Not a perfect scenario but the best I could find.

$(document).off("mouseover mouseout", ".child").find('.child').filter(function() {
  return !$(this).parents(".parent2").length;
}).on("mouseover mouseout", function() {
 console.log("new " + $(this).text());
});

Upvotes: 1

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

The jQuery .unbind() should do...

$(".parent2 .child").unbind("mouseover mouseout");

EDIT
Since .child are dynamically inserted, try this:

$(".parent2").find(".child").unbind("mouseover mouseout");

Upvotes: 1

Related Questions