Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent click events from firing on the draggable and/or childs #159

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,11 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
onDragEnd,
} = options;

/**
* Whether the element was dragged at least once ( to prevent mouse click event after drag )
*/
let wasDragged = false;

let active = false;

let translateX = 0,
Expand Down Expand Up @@ -378,6 +383,8 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {

if (e.button === 2) return;

wasDragged = false;

activePointers.add(e.pointerId);

if (ignoreMultitouch && activePointers.size > 1) return e.preventDefault();
Expand Down Expand Up @@ -440,6 +447,15 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
function dragEnd(e: PointerEvent) {
activePointers.delete(e.pointerId);

const preventClickAfterDragEnd = (e: MouseEvent) => {
if (wasDragged) {
e.preventDefault(); // Prevent click if it was dragged
e.stopPropagation();
}
};

listen('click', preventClickAfterDragEnd, { once: true, capture: true });

if (!active) return;

if (recomputeBounds.dragEnd) computedBounds = computeBoundRect(bounds, node);
Expand Down Expand Up @@ -516,6 +532,7 @@ export const draggable = (node: HTMLElement, options: DragOptions = {}) => {
fireSvelteDragEvent();

setTranslate();
wasDragged = true;
}

return {
Expand Down
8 changes: 7 additions & 1 deletion packages/svelte/demo/src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,10 @@
<input type="number" bind:value={$progressX} />
<input type="number" bind:value={$progressY} />
<div
on:click={() => {
console.log('clicked');
// throw new Error('Should not be clickable');
}}
use:draggable={{
position: { y: $progressY, x: $progressX },
onDrag: ({ offsetX, offsetY }) => {
Expand All @@ -201,7 +205,9 @@
},
}}
class="box"
/>
>
<div on:click={() => console.log('MEME')}>click me</div>
</div>
</div>
</main>

Expand Down
Loading