Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 583
Giovanni Bastianelli Avatar asked Nov 20 '25 05:11

Giovanni Bastianelli


2 Answers

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.

like image 150
Zakaria Acharki Avatar answered Nov 22 '25 18:11

Zakaria Acharki


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

like image 32
Mostafa Yousef Avatar answered Nov 22 '25 18:11

Mostafa Yousef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!