0

I'm trying to add event listeners to buttons on a webpage, my button contains several child elements, when I click my button I only need to get the data associated with the button, such as data attributes.

Even after adding an event.stopPropogation() into my on click handler, I'm still seeing that when I click directly over a h2 element that there's no data attributes logged.

What am I exactly missing from my code?

const button = document.querySelector('[data-toggle="collapse"]')

button.addEventListener('click', (e) => {
  e.stopPropagation()
  const target = e.target.dataset
  console.log(target)
}, false)
<body>
  <button type="button" data-target="hello" data-toggle="collapse">
  <div class="row">
    <div class="col">
      <h2>
        My heading 2
      </h2>
    </div>
  </div>
</button>
</body>
aerial
  • 1,188
  • 3
  • 7
  • 15
Ryan H
  • 2,620
  • 4
  • 37
  • 109
  • 1
    You have a serious misconception about how propagation works. Please take a look at [Introduction to events - Bubbling and capturing explained](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#bubbling_and_capturing_explained) – Erik Philips Oct 25 '21 at 15:29
  • `e.currentTarget.dataset` – epascarello Oct 25 '21 at 15:35

1 Answers1

0

Stop propagation works the other way round. You can see how it works here: What's the difference between event.stopPropagation and event.preventDefault?

What you need to do is to get the data from e.currentTarget instead of e.target.

const button = document.querySelector('[data-toggle="collapse"]')
button.addEventListener('click', (e) => {
    const target = e.currentTarget.dataset
    console.log(target)
}, false);

Also: Difference between e.target and e.currentTarget