1

I am sure this must already have been asked but I can't find it.

<div class=".clickable">
    <img src="my-big-button">
      Some text maybe
</div>

$(".clickable").click(function(e) {
    var el = $(this);
    if (el.prop("tagName") == "IMG")
    {
        el = el.parent("div");
    }
    el.addClass("selected");

});

I want to put the class on the div. But if the user clicks the image it is the image which is the target in the click event handler. The click event has 'bubbled up'. So my current code detects for this and 'elevates' the handler to the div. But there must be a better way of doing this?

Kropotkin
  • 353
  • 3
  • 10
  • In your code, `this` will *always* be the outer `.clickable` (unless you make the `` as well, which you don't want) – freedomn-m Jul 11 '22 at 14:00
  • In jquery, `this` is the `e.currentTarget`, looks like you think it's `e.target`. See [this answer](https://stackoverflow.com/a/10086501/2181514) – freedomn-m Jul 11 '22 at 14:03
  • Thank you @freedomn-m - and for the link. Yes- I see this is always currentTarget. – Kropotkin Jul 13 '22 at 14:58

1 Answers1

1

You can control the behavior by understanding how do events propagate/bubble in the DOM & how you can stop this process. The following snippet may explain the situation a bit more:

jQuery(document).ready(function($) {
  $(".clickable").click(function(e) {
    const el = $(this);

    // "this" in jQuery event handling is the same as e.currentTarget
    console.log("e.currentTarget is \"this\"", e.currentTarget === this)

    console.log(el.prop("tagName"))
    el.toggleClass("selected");
  });

  $(".clickable-stop").click(function(e) {
    e.stopPropagation() // this is why this is .clickable-stop
    const el = $(this);
    console.log(el.prop("tagName"))
    el.toggleClass("selected");
  });
})
.container {
  min-height: 500px;
}

.selected {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  In this case only the div is clickable:
  <div class="clickable">
    <img class="my-big-button" src="https://picsum.photos/50"> Some text maybe
  </div>
  <hr /> In this case both the div and the img is clickable:
  <div class="clickable">
    <img class="my-big-button clickable" src="https://picsum.photos/50"> Some text maybe
  </div>
  <hr /> In this case both the div and the img is clickable-stop, but only one of them can be clicked at a time:
  <div class="clickable-stop">
    <img class="my-big-button clickable-stop" src="https://picsum.photos/50"> Some text maybe
  </div>
</div>
muka.gergely
  • 8,063
  • 2
  • 17
  • 34