Question

I don't understand why, when using stopPropagation() or stopDefault() with jQuery, you have to introduce a param to the callback in the event handler function. How does the browser know what to pass in to that function? Also, why doesn't using this work?

Here's the code that works. I've bolded/asterisked the part that is confusing:

$(document).ready(function() {
   $(".see-photos").on("click", function(**event**) {
    event.stopPropagation();
    $(this).closest(".tour").find(".photos").slideToggle();
  });
  $(".tour").on("click", function() {
    alert("This should not be called");
  });
});

To me, it would make more sense this way. Note there is no event param for the callback in the handler function.

$(document).ready(function() {
  $(".see-photos").on("click", function() {
    $(this).stopPropagation();
    $(this).closest(".tour").find(".photos").slideToggle();
  });
  $(".tour").on("click", function() {
    alert("This should not be called");
  });
});
Was it helpful?

Solution

That's because jQuerys' .on() function passes the element who the event was fired from as this, not the event itself.

If you try to do the following:

$('a').on('click', function () {
   console.log(this);
});

You will see in your console the <a> tag that got clicked on. This is applicable to both the DOM click event as well as jQuery's. You can also see this <a> tag from event.target.*

If you want information about the event, then you need to inject it into your function as you've done so in your question:

$('a').on('click', function (event) {
    console.log(event);
});

This way, all of your event information is found in event. Likewise, it is only logical that you would stop propagating the event itself, as the element isn't propagating anywhere.

That being said, this and event.target are not the same

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top