SaschaM78
SaschaM78

Reputation: 4497

angular event firing on wrong element

Question:

I have a container with a bound (wheel) event listener containing some headings and paragraphs just for demo purposes. When I use the mouse wheel to scroll, the scroll event is occurring on one of the inner elements rather than on the container having the bound event.

Why is an event firing on a child element of a container rather than on the bound element itself?

Background:

I am playing around with angular on StackBlitz and wanted to implement an event listener on a <div> container to handle the scroll event:

  <div class="inner no-scroll" (wheel)="blockScroll($event)">

In my app.component.ts I created the event handler to be called:

blockScroll(e) {

    console.log(e);

    if (e.target !== e.currentTarget) {
      return;
    }

    let eO = e; // e.originalEvent;
    var delta = eO.deltaY || -eO.detail;
    e.target.scrollTop += delta * 30;

    e.stopPropagation();
    e.preventDefault();
}

In Firefox Developer Tools I see that the event is properly bound to the <div>:

Firefox Developer Tools

Now when I use the mouse wheel over the container I see that in nearly all cases the event target is not the bound <div> but rather a <h3> or <p> element inside of the container. I wonder why the wrong element is triggering the scroll event?

Upvotes: 0

Views: 695

Answers (1)

Barremian
Barremian

Reputation: 31125

This is the expected behavior.

  • target - element that triggered event (element directly under the mouse pointer at the beginning of the scroll)
  • currentTarget - element that listens to event (the div element in this case)

So if you were to point at the top of the container and begin scrolling, both target and currentTarget would point to the same div element. But once it's scrolled past the top of the container, the elements directly beneath the mouse pointer would be the <p> or <h3> elements.

Upvotes: 1

Related Questions