3

I'm trying to stop the propagation on an event of all the anchors in a div that has a click event attached but only the .click jquery function fire e.stopPropagation();, the .on('click', 'a', function()); don't.

Code example that works, the click on the anchor do not fire the click on the div when clicked

<div class="clickedDiv" data-url="http://myurl.com">
  <a class="clickedA">my link</a>
</div>

<script>
  $('.clickedA').click(function(e) {e.stopPropagation();});
  $('.clickedDiv').click(function(e) {
    var url = $(this).data('url');
    window.location.href = url;
  });
</script>

Code exampe that doesn't work, the click on the anchor fire both click, the anchor itself and the div

<div class="clickedDiv" data-url="http://myurl.com">
  <a class="clickedA">my link</a>
</div>

<script>
  $('.clickedDiv').on('click', 'a', function(e) {e.stopPropagation();});
  $('.clickedDiv').click(function(e) {
    var url = $(this).data('url');
    window.location.href = url;
  });
</script>
  • 3
    Delegate events function by letting the event propagate up to the parent. By the time it's reached the parent, it's already propagated out of the source element. – Taplar Nov 07 '17 at 16:06
  • 2
    Or, to put it the other way around - if you _had_ stopped the click event on the `a` from propagating, bubbling up - then your delegated handler would not even fire. – CBroe Nov 07 '17 at 16:08

2 Answers2

4

You should prevent the default action instead using e.preventDefault(), should be :

$('.clickedDiv').click(function(e) {
    e.preventDefault();

    var url = $(this).data('url');
    window.location.href = url;
}

NOTE : No need for the other click event :

$('.clickedDiv').on('click', 'a', function(e) {e.stopPropagation();});

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
1

First, you are missing

)

at the end of 2 scripts this could cause the problem.

Second, If this is just typo, the both code should have the same results, the event fires when click on the div only and didn't fire when click on the anchor.

check this fiddle here https://jsfiddle.net/3tg96ru1/2/

Third, a better way to do that is to do it in the same function and check if the clicked element is not the anchor then execute the function like this:

    $('.clickedDiv3').click(function(e) {

    var target = e.target;
if (!$(target).is('.clickedA3')) {
        alert('fffff');
    } });

for more details about difference between .on('click') vs .click() check this link: Difference between .on('click') vs .click()