cy23
cy23

Reputation: 402

How do I access an event's actual target when a child element triggers the event?

I'm listening on this button for a click event, which would run toggleSubMenu() method of a Vue instance. I want it so that when the button is clicked I can get the event.target's parentNode which would be the div with a class of sub-menu-sibling, and then it's nextElementSibling which would be the div with a class of sub-menu. This is my HTML structure.

<div class="sub-menu-sibling">
  <button @click.stop="toggleSubMenu($event)" class="btn" type="button" name="button">
    <svg class="bi bi-chevron-right" width="14px" height="14px" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
      <path fill-rule="evenodd" d="M4.646 1.646a.5.5 0 01.708 0l6 6a.5.5 0 010 .708l-6 6a.5.5 0 01-.708-.708L10.293 8 4.646 2.354a.5.5 0 010-.708z" clip-rule="evenodd" />
    </svg>
    Show Menu
  </button>
</div>
<div class="sub-menu">
  <!-- menu items -->
</div>

This is my Vue app

const Menu = Vue.createApp({
  methods: {
    toggleSubMenu: function(event) {
      const subMenus = document.querySelectorAll("#categoriesMenu .sub-menu");
      let targetSubMenu = event.target.parentElement.nextElementSibling;

      targetSubMenu.classList.toggle('show');

      subMenus.forEach((sub) => {
        sub.classList.contains('show') && sub != currentSubMenu ? sub.classList.remove('show') : ''
      });
    }
  }
})

The problem is that when a user clicks directly on the svg icon inside the button, it becomes the event.target, which breaks my whole expectation. How do I get it to listen primarily on the button's surface alone?

Upvotes: 0

Views: 827

Answers (2)

cy23
cy23

Reputation: 402

===UPDATE
I didn't know event.currentTarget existed.

Upvotes: 1

user7396942
user7396942

Reputation:

You can apply stop propagation on the action button

 const stopPropagation = event => {
    event.cancelBubble = true
    event.preventDefault()
    if (event.stopPropagation) event.stopPropagation()
  }

and

const toggleSubMenu = () => {
 stopPropagation()
 ...
}

Upvotes: 1

Related Questions