0

I want to add custom context menu to my list element, but I have problem with detecting correct item. I have a list which contain many positions which represent each opened tab in browser.

<div class="position" data-id="0">
    <div class="imgContainer"><img src="./favicons/trello.png"></div>
    <div class="info">
        <div class="title">Productivity | Trello</div>
        <div class="address" title="https://trello.com/">
            <span class="protocol">https://</span><span class="host">trello.com</span>
        </div>
    </div>
</div>

And I have also js code to capture right click on each position.

let position = document.querySelector(".position");

    position.addEventListener("contextmenu", event => {
        event.preventDefault();
        event.stopPropagation();

     });

For the test i have only one position. Problem is that event target doesn't contain my position as a target, but different children of that element. I log that event to the console, but no one property contain correct element.

contextmenu {
    currentTarget: null,
    explicitOriginalTarget: <div class="info">,
​    orginalTarget: <div class="info">,
    srcElement: <div class="info">,
    target: <div class="info"
}

Event listener has been added to position element, so I was expected that one of these properties will refer to correct position element, to extract data-id from it.

Is there simple way to get correct element as a target (position element, not any child of it)?

  • `document.querySelector(".position")` will only find the first such element, and you’re binding the event listener only to that one. Use [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple events — it’s more maintainable, and applies to dynamically added elements. See [the tag info](https://stackoverflow.com/tags/event-delegation/info) and [What is DOM Event delegation?](https://stackoverflow.com/q/1687296/4642212). Also, use `.closest(".position")` if you want an ascendant of the `.target` element. – Sebastian Simon Feb 15 '21 at 22:34
  • 1
    [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+get+container+of+event+target) of [Click event target gives element or it's child, not parent element](https://stackoverflow.com/q/50149925/4642212). Note the [documentation](https://developer.mozilla.org/en-US/docs/Web/API/Event/currentTarget): _“Note: The value of `event.currentTarget` is only available while the event is being handled. If you `console.log()` the `event` object, storing it in a variable, and then look for the `currentTarget` key in the console, its value will be `null`.”_ – Sebastian Simon Feb 15 '21 at 22:44
  • @SebastianSimon Thanks for useful information. Hmm... I didn't know that currentTarget is only available while the event is being handled. Next time I need to read more documentation. – Krzysztof Boronowski Feb 16 '21 at 19:14

0 Answers0