Search code examples
angulardrag

When dragging fast cursor looses element - angular


https://stackblitz.com/edit/stackblitz-starters-ce1irg?file=src%2Fmain.ts

 mouseDown: any = false
  centiesX: any
  centiesY: any
  active: any = {
    node: undefined
  }
  @HostListener('mousedown', ['$event'])
  mousedown(e: any) {
    this.mouseDown = true
    this.active.node = document.getElementsByClassName('n-1234567')[0]
    this.active.node.style['position'] = 'absolute'
    this.centiesX = e.clientX - +this.active.node?.style.left.split('px')[0]
    this.centiesY = e.clientY - +this.active.node?.style.top.split('px')[0]
  }
  @HostListener('mousemove', ['$event'])
  mousemove(e: any) {
    if (this.mouseDown) {
      this.active.node.style.top = e.pageY - this.centiesY + 'px'
      this.active.node.style.left = e.pageX - this.centiesX + 'px'
      // if (typeof +this.active.name === 'number' && this.active.name != false) {}
    }
  }
  @HostListener('mouseup', ['$event'])
  mouseUp(e: any) {
    this.active.node.style['position'] = 'absolute'

    this.mouseDown = false
  }
//HTML
<div class="n-1234567"></div>

Should be simply a draggable square. If you go back and forth quickly cursor looses touch of element. I can't figure out why.

Thanks.


Solution

  • The problem is the mousemove part. Your write: @HostListener('mousemove', ['$event']) - this is fine, but the mousemove is set to the component self (so your block). use ' window:mousemove' and the function handle if the cursor is outside the block (fast moving), too:

      @HostListener('window:mousemove', ['$event'])
      mousemove(e: any) {
        if (this.mouseDown) {
          this.active.node.style.top = e.pageY - this.centiesY + 'px';
          this.active.node.style.left = e.pageX - this.centiesX + 'px';
        }
      }