1 year ago

#351371

test-img

pinkfloyd90

EventListener added to parent div, but event.target becomes children element if clicked on

I'm working with card shaped divs that I need to be clickable. I'm using JS (stimulusJS) to add an EventListener to them so when the user clicks on the card, the event listener is fired adding some CSS classes and populating some hidden fields with data that comes from the divs dataSet.

card

<div class="card d-flex flex-column data-selectable-target="selectable" data-pricing-model-value="flat_fee">
   <div class="self-end">
      <strong>
        <span class="mr-3" data-toggle="tooltip" title="<%= t(".tooltip") %>"><%= icon("exclamation-circle", classes: "h-4 w-4") %></span>
      </strong>
   </div>
   <h5><%= t(".title") %></h5>
   <p> <%= t(".description") %></p>
</div>

JS controller

import { Controller } from 'stimulus';

export default class extends Controller {
  static targets = ["selectable"]

  connect() {
    this.selectableTargets.forEach((element) => {
      element.addEventListener("click", (event) => {
        this.select(event.target);
      });
    })
  }

  select(element) {
    element.classList.add("selected")
    this.selectableTargets.forEach((target) => {
      if (target != element) {
        target.classList.remove("pricing-model-selected")
      }
    })
  }
}

Problem: I'm using event.target expecting to get the parent div to which I added the EventListener. Instead, if I click on the card's h5 or p elements, they become the event.target messing up my implementation. Is there anything that could be done to ensure that event.target always refers to the parent div to which the EventListener was added?

javascript

html

stimulusjs

0 Answers

Your Answer

Accepted video resources