Arne
Arne

Reputation: 3

Can't get JS to bubble event

I've got a structure as in this fiddle: https://jsfiddle.net/Arne651/s8wbeyh5/11/

<ul id="ul">
  <li class="test">
    <p>
      Some text
    </p>
  </li>
  <li class="test">
    <p>
      Some text
    </p>
  </li>
  <li class="test">
    <p>
      Some text
    </p>
  </li>
</ul>

I've got an event on a <ul> element, in which im trying to do something with the <li> element that was clicked. This <li> element contains a <p> element and the event doesn't seem to bubble upwards.

let ul = $("#ul")
ul.on("click", function(e) {
    let clicked = $(e.target)
    console.log(clicked)
    if (clicked.hasClass("test")) {
        console.log("li triggered")
    }
})

I don't want events on all the <li> elements because the list can get quite long and a single event feels neater.

Upvotes: 0

Views: 85

Answers (2)

hobomaan
hobomaan

Reputation: 151

When clicking the text, the target is the p tag.

Getting the closest li might not be the best way to do this but this works.

ul.on("click", function(e) {
    let clicked = $(e.target).closest('li');
    console.log(clicked);
    if (clicked.hasClass("test")) {
        console.log("li triggered");
    }
});

Upvotes: 1

Abdelrahman Hussien
Abdelrahman Hussien

Reputation: 505

you can add the click on the li only try this

let li = $("#ul li.test")
li.on("click", function(e) {
  console.log("li triggered");
})

I am first fetching all li that have calse test then add the listener on them.

Upvotes: 0

Related Questions