sonam
sonam

Reputation: 3770

stop event propagation on element in jquery

I have an element as show below:

<div id="treeTable123" class="collapsed">
<div id="test"></div>
</div>

I have binded on click function to div with id 'test' using jquery. function1:

 $(document).delegate('#test', 'click', function(e){
   ....
 });

I have another binded click function to other elements as: function2:

  $('[id^="treeTable"]').delegate('.collapsed', 'click', function(e){
  });

When I click div with id 'test' both events are fired. So I want to prevent the event in the function 2 on clicking on event inside function 1. How can i do that?

Upvotes: 1

Views: 886

Answers (4)

sonam
sonam

Reputation: 3770

$('[id^="treeTable"]').delegate('.collapsed', 'click', function(e){
   if($(e.target).closest('#test').length === 0) {
      // code placed inside this condition is not executed on clicking the element #test
   }
});

Upvotes: 1

Musa
Musa

Reputation: 97717

As you have it, its not possible. You can do it if you don't use delegation as the event has to bubble up to the delegate target for the event handler to fire. So function2 will fire before function1 and you can't prevent a it from firing after it fired.

 $('#test').on('click', function(e){
     e.stopPropagation();
   ....
 });

http://jsfiddle.net/r5JaL/

Upvotes: 0

rahul
rahul

Reputation: 7663

you can simple use e.stopPropagation()

More Info

Upvotes: 0

bjornd
bjornd

Reputation: 22951

Just call the e.stopPropagation() form the first callback. Here is a demo http://jsfiddle.net/eyXT7/2/.

Upvotes: 0

Related Questions