Resizing a div dynamically based on its parent's position using JavaScript

I've been working on a code to dynamically resize multiple divs. The original code only resized one element, but I modified it to handle multiple div resizers.

However, I'm facing an issue where there is a gap between the mouse and the div while resizing. My goal is to ensure each element is resized in relation to the exact mouse location relative to its parent position. I welcome any new approach that can change my perspective on this matter. It's not necessary to use the resize nodes; directly manipulating the div borders is also an option.

What I've accomplished so far:

- Made multiple divs resizable based on mouse location.

- Stored initial location information in a function.

- Calculated the difference between child and parent elements.

What I aim to achieve:

- Ensure that the div stays under the mouse location without any space between them during resizing.

After several attempts at resizing, I noticed a gap caused by margins and paddings of parent elements, resulting in resizing with a gap between the div and the mouse. A recursive solution is needed to accurately resize and reposition the divs. Another approach might involve calculating only x, y, w, h values inside the parent, but I need guidance on how to implement this effectively using the mouse...

For a clearer demonstration, you can refer to the following CodePen: https://codepen.io/BerkerYuceer/pen/gOYwqdb

Answer №1

To retrieve the value of the transform property using regex and adjust the coordinates as needed, you can utilize getComputedStyle along with applying a reciprocal scale factor to the required coordinates. I managed to resolve the issue specifically for the container oriented towards the East direction (my comprehension of coordinate geometry is somewhat limited):

let match = getComputedStyle(element)
           .transform.match(/matrix\((-?\d*\.?\d+),\s*0,\s*0,\s*(-?\d*\.?\d+),\s*0,\s*0\)/);
let scale = 1; //for regular individuals
if (match && +match[1] != 0)
   scale = 1 / +match[1]; //to reverse the applied transformation

Sample:

(...JavaScript code snippets continue here...)

You can also achieve this by following this method presented in another thread.

var element = document.querySelector('...');
var scaleX = element.getBoundingClientRect().width / element.offsetWidth;

"This technique works because getBoundingClientRect provides the actual dimensions while offsetWidth/Height represent the unscaled size."

Edit: Added window.scrollX/Y for usability on scrolled pages.

This method remains reliable across different sections of the page, even when dealing with scaled objects.

Answer №2

Have you ever considered using jQuery resizable? It can be a real time-saver and make your life easier :)

If you want to see how it works, check out this simple example: https://jsfiddle.net/maehy5tj/1/

It's really all you need to do to get started :)

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8>
  ....(omitted for brevity)...
</body>
</html>

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

What is preventing the MenuItem component from functioning as a Link in React Material-UI?

Hey there! I've been trying to implement a popover menu that changes the URL and component after clicking on an item, but unfortunately it's not working as expected. I created a setup in this sandbox: https://codesandbox.io/s/romantic-surf-40p19? ...

What is the best way to arrange list items in this manner?

I am facing challenges with aligning elements properly on the navigation bar. I would like the words (home, players, about, contact) to be vertically centered in relation to the heart logo. Here is how it currently appears: This is how I want it to look ...

Display/Conceal the UL subelement when selected

I've been struggling to toggle the visibility of some ul checkboxes when their parent is clicked. Despite my best efforts, I just can't seem to make it work! Could someone lend a hand in getting this functionality working? Essentially, I need th ...

While creating a customer profile sample, I encountered an issue where I received an error message stating "POST http://localhost:3000/cusprofiles/add 400 (Bad Request)" when attempting to add data

I'm having trouble creating a customer profile for a vet clinic in my code. I'm unable to add and edit customer details, and I'm not sure where I've made a mistake. The only method that seems to be working is the GET method. Can someone ...

Is there a way to utilize AJAX to submit a request to a PHP XML-RPC server?

To communicate with my XML-RPC PHP server from a PhoneGap app, I intend to send an XML-RPC request using AJAX. The request should contain the method, parameters, and all necessary details. ...

What significance does the slash hold in a package name when using require for an npm package?

When we "require" non-local NodeJS modules, what does the slash in the module name signify? For instance: from the GitHub page of the ShellJS npm module (link: https://github.com/shelljs/shelljs#javascript) require('shelljs/global'); requir ...

Tips for troubleshooting a node module that is part of a build process

When working on my applications, I often rely on the NPM package.json to handle my build tools. However, I've come across a module that seems to have a bug. I'm eager to debug it, but I'm unsure how to do so within the context of the build t ...

Incorporating geocoding functionality in an asp.net mvc project and looking to efficiently transfer latitude and longitude data from JavaScript to a controller function

UPDATED. Following your suggestions, I implemented the function as shown below: [HttpPost] public ActionResult populate_place(string lati, string longi) { list_placesModels list_place = new list_placesModels(); list_place.Latitude = lati; li ...

Is it possible to create a functionality in Google Sheets where a cell, when modified, automatically displays the date of the edit next to it? This could be achieved using a Google

Here is the current code snippet I have: function onEdit(e) { var range = e.range; var val = range.getValue(); var row = range.getRow(); var col = range.getColumn(); var shift = 1; var ss = SpreadsheetApp.getActiveSheet().getRange(row, (col+ ...

Is it possible to view the code within the .js files located in the api directory of NextJS using web browsers?

Is it possible to view the code of ".js files" in the "api folder" of NextJS using browsers? I came across a post on Stack Overflow where someone asked if Next.js API is back-end, and one of the answers stated: The back-end or server-side of Next.js res ...

The onScroll event is failing to trigger when scrolling to a particular div on Next.js

Is there a way to fetch data when a specific div comes into view on a SSR page in Next.js? I attempted using the onScroll event on the div, but it doesn't seem to be triggering. Any suggestions? function handleScroll() { console.log("scrolled ...

What is the best way to adjust the spacing between elements using CSS?

I am attempting to achieve this layout using CSS: The margin between each element is set to 10px. The height of the textarea is 100px and the width is 150px This snippet shows some HTML code for your reference: main form label { ...

Is it possible to swap out a webpage link for a different one based on the size of the screen?

I designed a website for a friend: www.donjas-wellbeingforkids.co.uk I set up a Facebook Messenger Contact Us Link directly from the contact page here: donjaswell-beingforkids contact It's functional on desktop, where it seamlessly opens Facebook Me ...

What is the best method for handling and analyzing error objects within a catch statement following an API request?

When working with an API, dealing with complex error objects is a common occurrence. https://i.sstatic.net/0iK9t.png Depending on the specific API, the error messages can be quite informative and sometimes you may want to directly display them to the use ...

Is it possible for an object to be null even when its type is object

There's an issue that I can't seem to replicate. Personally, I'm not experiencing any errors but bugsnag reports that some users are encountering them. Take a look at snippet line 6 for more information. let lang = this.$store.state.lang ...

Transform all characters to lowercase, then capitalize them using only CSS

I came across a discussion on this topic at: First lowercase the text then capitalize it. Is it possible with CSS? However, the solution provided was not purely based on CSS. I have a div that contains the following text: <div> RaWr rAwR </div&g ...

What is the Best Way to Create a Form Inside a Box?

Hello there! I am trying to create a form underneath the box labeled "New Referral," but I'm having trouble figuring it out. I would like to include sections for first name, last name, date of birth, phone number, email, and address under the box. Any ...

What is the best way to create a video that adjusts to different screen sizes within

I am working on the responsive version of client's website and I stumbled upon this issue - when I make smaller the browser window, the youtube video is not centered - the padding-right: 10px; is ignored - why? How could I fix that? Here is the CSS ...

How to shift an image to the right side of the navbar

Is it possible to change the position of an image within a navbar from left to right? I have tried using the float property but it doesn't seem to work. .logo-img{ float: right; margin: 0px 15px 15px 0px; } <a class="navbar-brand logo-img" ...

Webpack: Live reloading is not functioning properly, however the changes are still successfully compiling

Could someone help me understand why my React application, set up with Webpack hot reload, is not functioning properly? Below is the content of my webpack.config.js: const path = require('path'); module.exports = { mode: 'development&apo ...