1

My Code is like following in html:

<li class="arrow">    
    <div>
        <a href="javascript:void(0);" class="anchor">remove</a> 
    </div>                      
</li>

And I bind my elements using deligate() jquery method (because elements appear dynamically)

$obj.delegate(".arrow", "click", function() {
    alert("clicked on arrow");
});

$obj.delegate(".anchor", "click", function(event) {
     event.stopPropagation();
     alert("anchor clicked");
});

My Problem is, when I click on ".anchor" then both events occurs. can anyone tell me how to use event.stopPropagation() in this context? I tried like the above but not working. Is there any other way to do this?

EDIT: I tried with calling event.isPropagationStopped(), and it returns true. but still both events called.

animuson
  • 53,861
  • 28
  • 137
  • 147
Bhupi
  • 2,928
  • 6
  • 34
  • 51

2 Answers2

4

There is limitations when delegate or live is used and stopPropagation.

You return false in you handler to prevent both eventPropagation and default

Try

$obj.delegate(".anchor", "click", function(event) {
     alert("anchor clicked");
     return false;
});
Peeja
  • 13,683
  • 11
  • 58
  • 77
Zimbabao
  • 8,150
  • 3
  • 29
  • 36
  • wow, a lot has happened in the 4 minutes it took to write my answer :) - is there any reason you have left .stopPropagation() in the code? I don't believe it does anything in this context – Stuart Burrows Mar 05 '11 at 10:21
  • No reason. I just copied the part. I left it there by mistake. – Zimbabao Mar 05 '11 at 10:24
  • To make it clearer to the next person who comes along, I've removed stopPropagation() from the answer (if my edit goes through). – Peeja Oct 30 '13 at 14:28
1

My understanding is that with .delegate and .live you need to return false. I believe this is because of how the event is attached - not to the element but to it's ancestor.

Here is an example: http://jsfiddle.net/G3k8Z/

Stuart Burrows
  • 10,824
  • 2
  • 34
  • 33