Discover the position of a div relative to another div using ng-drag-drop

I'm currently working on a web application that allows users to create their own identity cards.

For this project, I am incorporating the ng-drag-drop library from

https://www.npmjs.com/package/ng-drag-drop
.

The main goal is to obtain the coordinates of a div box within a larger div container.

In specific, I am looking for the (x,y) position relative to the outer div.

Here are the key objectives:

  1. Position the inner div at a specified location within the outer div.
  2. Allow draggable functionality and retrieve updated coordinates.

Issue: When I programmatically reposition the box and then move it around, the x,y values turn out to be negative –

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;
}

Answer №1

When you change an element's position using css transform, the transform values represent the change in position from its original location.

Even when an element is moved with transform, its original position remains the same, as the new position is always calculated based on the

original position + change in position
.

If you know the original position of the element, you can add the transform values to determine the current position.

The code below will help you find the current position of the element in relation 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues with CSS list hovering functionality in Google Chrome

One of the challenges I'm facing with my HTML list is that when hovering over each list item, the text along with the bullet point should change color. Here's the structure: <ul> <li>A bullet point</li> <li>Another ...

The design of RESTful web applications with a client-server architecture

I need clarification on how client-server architecture should function for a modern web application with a RESTful backend. For a web app, the client is typically the browser while the server is the web server. Programatically speaking, there are componen ...

Error in JavaScript: Uncaught TypeError - Unable to access the "left" property of an undefined object

This error is really frustrating and I've come across several inquiries regarding this console issue. It's not providing enough information in the chrome console for me to effectively troubleshoot. /** * Adjustment of dropdown menu positio ...

Tips for setting up a responsive dropdown field in an Angular 6 reactive form for an Edit page

When creating a drop down field with API values, I encountered an issue where all data was displayed on the edit page instead of just the previously stored value. The drop down field showed all options instead of the selected one. Below is the code for the ...

Looking to change the input field names by increasing or decreasing when clicking on a div using jQuery?

As a beginner in the world of jQuery, I am working on mastering some basic concepts. Currently, my goal is to create auto incrementing/decrementing input field names within a 'div' when clicking on an add/remove button. Below is the HTML code I a ...

When utilizing jQuery's .on() method, sometimes the data being passed to the handler may appear

I have three anchor tags that are dynamically added from an ajax $.get() response. Whenever one of them is clicked, I want to trigger a second request. The parameters for the second request should be set based on the global data attributes in these an ...

Managing consecutive synchronous side effects that are dependent on each other using React hooks

I am currently in the process of transitioning my application from using Redux to the new context and hooks, but I am facing challenges when it comes to handling a series of synchronous side-effects that rely on the response of the previous one. In my exi ...

A growing flexbox container that expands to a specific height before allowing for scrolling

In the case of a fixed height container with two vertical divs, I am aiming for the first div to be as tall as its content, up to 80% of the parent div's height. After that point, the content within the first div should scroll. The second div will the ...

What other options are available besides componentDidUpdate for retrieving the chosen date from a date picker and including it in an API request?

Currently, I am utilizing react-dates to implement a datepicker feature. Whenever the user modifies the date, it updates a prop that is then sent to the backend as a parameter in a query to fetch specific results for that particular day from the database. ...

Calculation Error in JavaScript/JQuery

I've been working on a JavaScript function to calculate the sum of values entered into textboxes, but it seems to be giving me inaccurate results in certain cases. Check out the FIDDLE here Enter values : 234.32 and 32.34 Result: 266.6599999999999 ...

Why is it that in IE9, submitting a basic form using jQuery doesn't seem to work?

Take a look at the code snippet below: <html> <head> <style type="text/css"> #myform {display:none;} </style> </head> <body> <button type="button" id="uploadbutton">Upload Images</button> <form name="myf ...

Trouble with nested components not refreshing correctly within VueJs

I've just started working with Vue and I'm currently developing a forum-style application that allows nested comments. Within this structure, there are two main components: PostForum and Comment. The PostForum component consists of an input box f ...

Integrating TypeScript into an established project utilizing React, Webpack, and Babel

Currently, I am in the process of integrating Typescript into my existing React, Webpack, and Babel project. I aim to include support for file extensions such as [.js, .ts, .tsx] as part of my gradual transition to Typescript. I have made some progress, b ...

Clerk Bug: The UserResource type returned by useUser() does not match the @clerk/types

When attempting to pass the user obtained from useUser(), an error occurred: The 'UserResource' type is lacking the required properties 'passkeys' and 'createPasskey' from the 'UserResource' type Upon investigating ...

issues arising from a growing css division

I am facing an issue where the tiles on my webpage expand on hover, but some of them are partially covered by neighboring tiles. How can I resolve this problem? Here is the CSS code snippet: .tile { position: absolute; width: 86px; background-color ...

analyzing strings by comparing their characters to another string

In a scenario where I have two strings; let's call them string a="a-b-c" and string b="a-b". I am looking to determine whether every letter in string b is present within string a. ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

The CSS background image is not functioning

.menubar li { float: left; width: 115px; text-align: center; background-image: url(js/left_main_bg_image.gif); } Having issues with the background image not displaying properly in IE, Firefox, and Chrome. I've tried adding it to a tab ...

Can you explain the concept of the "node module wrapper function" in the context of Node.js?

Can someone explain to me the concept of a "module wrapper function" and how it affects my code? (function (exports, require, module, __filename, __dirname) { }); ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...