Skip to content

Drag 'n Drop example is broken #188

@hbarcelos

Description

@hbarcelos

I took the example code and modified it a little bit, using modern Javascript patterns:

const flyd = require('flyd');
const takeUntil = require('flyd/module/takeuntil');

function $(sel) {
  return document.querySelector(sel);
}

document.addEventListener('DOMContentLoaded', () => {
  const dragElm = $('#drag');

  const mouseDown = flyd.stream();
  const mouseMove = flyd.stream();
  const mouseUp = flyd.stream();

  dragElm.addEventListener('mousedown', mouseDown);
  document.addEventListener('mousemove', mouseMove);
  document.addEventListener('mouseup', mouseUp);

  const mouseDrag = flyd.chain(md => {
    const startX = md.offsetX;
    const startY = md.offsetY;

    console.log('Got mouse down!');
    console.log('Initial element position:', { startX, startY });

    return takeUntil(flyd.map(mm => {
      console.log('Got mouse move!');
      console.log('Current mouse position:', {
        x: mm.clientX,
        y: mm.clientY,
      });

      return {
        left: mm.clientX - startX,
        top: mm.clientY - startY,
      };
    }, mouseMove), mouseUp);
  }, mouseDown);

  flyd.on(({ top, left }) => {
    console.log('Current element position', { top, left });
    dragElm.style.top = `${top}px`;
    dragElm.style.left = `${left}px`;
  }, mouseDrag);
});

The behavior I can observe is that the drag 'n drop only works in the first drag. Then, I can no longer drag the box.

I added some logs to see what was going on and what I get is:

  • The mousemove event continues to be fired after the mouseup event happens (what I would expect, because it's bound to the document.
  • The on callback is executed only once.

I guessed I was doing something wrong, so I copy/pasted the example code, but the behavior was still the same.

What exactly is wrong here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions