Question: Why .on('click', 'a' ) do not execute e.stopPropagation(); on the anchor selector?

Question

Why .on('click', 'a' ) do not execute e.stopPropagation(); on the anchor selector?

Answers 2
Added at 2017-11-07 17:11
Tags
Question

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>
Answers to

Why .on(&#39;click&#39;, &#39;a&#39; ) do not execute e.stopPropagation(); on the anchor selector?

nr: #1 dodano: 2017-11-07 17:11

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.

nr: #2 dodano: 2017-11-07 20:11

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()

Source Show
◀ Wstecz