Find relative position of div inside another div (ng-drag-drop)

Viewed 350

I am preparing a web app which allows user to design Identity cards.

I am using ng-drag-drop https://www.npmjs.com/package/ng-drag-drop for the same.

I wish to get co-ordinates of a div box inside a bigger div box.

As per the image, I want (x,y) with respect to outer div

Things to achieve:

  1. place inner div at specific position inside div
  2. drag around -- fetch new co-ordinates

Problem : when I reposition the box programmatically and then move it around, the x,y values are coming negative –

**Check the Image here**

HTML:

<div class="card-boundary" #boundary>
        <img width="1039" height="673" [ngStyle]="bgStyle" />
        <div cdkDragLockAxis="elem.dragLock" (cdkDragEnded)="dragEnd($event)" (cdkDragStarted)="onElemClick(elem,$event)" cdkDragBoundary=".card-boundary" cdkDrag *ngFor="let elem of elemList" [ngClass]="{'example-box-selected':(selectedElem && elem.field == selectedElem.field)}"
              (click)="onElemClick(elem,$event)" class="example-box" style="text-align: start" [ngStyle]="elem" #item>
             {{elem.sample}}
        </div>
</div>

Typescript:

 dragEnd(event: CdkDragEnd) {
    const transform = event.source.element.nativeElement.style.transform;
    let regex = /translate3d\(\s?(?<x>[-]?\d*)px,\s?(?<y>[-]?\d*)px,\s?(?<z>[-]?\d*)px\)/;
    var values = regex.exec(transform);
    this.selectedElem.startX = +values[1];
    this.selectedElem.startY = +values[2];
  }

CSS:

.card-boundary {
    width: 1039px;
    height: 676px;
    max-width: 100%;
    position: relative;
    background-color: #fff
}

.bg-boundary {
    width: 1039px;
    height: 676px;
    max-width: 100%;
}

.example-box {
    cursor: move;
    position: relative;
    z-index: 1;
}

.example-box-selected {
    cursor: move;
    background: #eee;
    position: relative;
    z-index: 1;
}
1 Answers

When the position of an element is changed using css transform, the values of transform indicate the position change from its' original position.

Also when an element is moved using transform, its' original position will never change, as the new position should always be calculated from original position + change in position.

So if you can get the original position of the element, you can add the transform values to the original position values to get the current position.

The below code will give you the current position of the element with respect to its' offsetParent.

dragEnd(event: CdkDragEnd) {
  const element = event.source.element.nativeElement;
  const transform = element.style.transform;
  let regex = /translate3d\(\s?(?<x>[-]?\d*)px,\s?(?<y>[-]?\d*)px,\s?(?<z>[-]?\d*)px\)/;
  var values = regex.exec(transform);
  this.selectedElem.startX = element.offsetLeft + +values[1];
  this.selectedElem.startY = element.offsetTop + +values[2];
}

PS: offsetParent = 'closest positioned parent' || document.body

Related