2

I have a span tag inside an anchor tag. When span is clicked I want the link to not get followed, that is I want to stop the click on span to trigger(bubble up) click on anchor tag. For that I used stopPropagation as:

$("a span").click(function(e){
  e.stopPropagation();      
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://stackoverflow.com">
  hello <span> click here </span>
</a>

As you can see the click event is still propagated to anchor tag. Instead, if I use e.preventDefault() then that seems to stop the bubbling up. Why isn't the stopPropagation stopping the propagation of click event?

Matt Gibson
  • 14,616
  • 7
  • 47
  • 79
user31782
  • 7,087
  • 14
  • 68
  • 143
  • Because of the event flow. Review the following: https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-flow-capture – Kramb May 04 '17 at 16:20
  • Check this fiddle: https://jsfiddle.net/Slico/u88u7tas/1/ – Slico May 04 '17 at 16:32
  • 1
    @Slico think you're missing some parentheses after `isPropagationStopped`. It returns the function itself, rather than `true`. – freginold May 04 '17 at 16:35
  • You are right, thank you. Here is the updated fiddle https://jsfiddle.net/Slico/u88u7tas/2/ – Slico May 04 '17 at 17:21

1 Answers1

4

e.preventDefault() is what you want. What you're describing isn't a result of event propagation, it's a result of the default behaviour of a link which is what you're trying to prevent.

Consider the following example:

$('a span').click(function(e) {
  e.stopPropagation();      
});

$('a').click(function(e) {
  alert('propagated!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://stackoverflow.com">
  hello <span> click here </span>
</a>

Had e.stopPropagation() not been called, the click handler for the anchor itself would be called and you'd get the alert.

André Dion
  • 21,269
  • 7
  • 56
  • 60
  • Ooops just posted something just like yours... deleting it. However, your snippet still doesn't show the point, because it navigates away. If you add a onbeforeunload, the user can cancel the page from being unloaded and observe that the direct handler on A wasn't called. – Ruan Mendes May 04 '17 at 16:39
  • So the actual browsers' implementation is to follow `href` of parent anchor tag. Do all browsers do the same? Is this behavior specified by w3c? – user31782 May 04 '17 at 16:46
  • 1
    @JuanMendes, a fair point, but if `e.stopPropagation()` had not been called, the `alert` would block the navigation until it's dismissed. – André Dion May 04 '17 at 16:51
  • That's true, probably a good idea to explain that in the answer – Ruan Mendes May 04 '17 at 17:14