Skip to content

Commit

Permalink
Fix getEventListenerTarget when target element is not an instance o…
Browse files Browse the repository at this point in the history
…f `HTMLElement` (#335)

For example, when the target element is an SVGElement, the event listener target returned was the owner document instead.

This causes issues with touch events when the `target` is an SVGElement. If the `event.target` element is removed from the document events will still be targeted at it, and hence won't always bubble up to the window or document anymore. If there is any risk of an element being removed while it is being dragged, the best practice is to attach the event listeners directly to the target.
  • Loading branch information
clauderic committed Jun 17, 2021
1 parent cf8d6b1 commit dbe0087
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/fix-listener-target.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@dnd-kit/core": patch
---

Fix `getEventListenerTarget` when target element is not an instance of `HTMLElement`
2 changes: 1 addition & 1 deletion packages/core/src/sensors/utilities/Listeners.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ export class Listeners {
handler: EventListenerOrEventListenerObject;
}[] = [];

constructor(private target: HTMLElement | Document | Window) {}
constructor(private target: EventTarget) {}

public add(
eventName: string,
Expand Down
9 changes: 7 additions & 2 deletions packages/core/src/sensors/utilities/getEventListenerTarget.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import {getOwnerDocument} from '../../utilities';

export function getEventListenerTarget(
element: EventTarget | null
): HTMLElement | Document {
return element instanceof HTMLElement ? element : getOwnerDocument(element);
): EventTarget | Document {
// If the `event.target` element is removed from the document events will still be targeted
// at it, and hence won't always bubble up to the window or document anymore.
// If there is any risk of an element being removed while it is being dragged,
// the best practice is to attach the event listeners directly to the target.
// https://developer.mozilla.org/en-US/docs/Web/API/EventTarget
return element instanceof EventTarget ? element : getOwnerDocument(element);
}

0 comments on commit dbe0087

Please sign in to comment.