Is it possible for a draggable position:absolute div to shrink once it reaches the edge of a position:relative div

I am facing an issue with draggable divs that have position:absolute set inside a position:relative parent div. The problem occurs when I drag the divs to the edge of the parent container, causing them to shrink in size. I need the draggable divs to maintain their original size even when they are outside the boundaries of the parent container. Unfortunately, I am unable to find a solution to this problem.

Here is the link to my codepen demonstrating the issue

    <div id="all">
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
        <div class="move txtbox">
            <div class="topper">test test</div>
            <span id="test">test test etst test test test</span>
        </div>
    </div>
    <script src="move.js"></script>
* {
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.1;
    margin: 0;
}

#all {
    position: relative;
    margin: 0 auto;
    width: 50%;
    height: 100vh;
}

.move {
    cursor: move;
    position: absolute;
}

.txtbox, .topper {
    background-color: lightgrey;
}

.txtbox {
    min-height: 70px;
    max-width: 250px;
}

.topper {
    font-size: .625em;
    border-bottom: 1px solid black;
    padding: 2px;
}
const els = document.querySelectorAll(".move");
els.forEach((name) => {
  dragElement(name);
});

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;
  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = elmnt.offsetTop - pos2 + "px";
    elmnt.style.left = elmnt.offsetLeft - pos1 + "px";
  }
  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

Answer №1

It is completely acceptable because an absolutely positioned element will adjust its content based on the dimensions of its relative or absolute parent. Simply specify the width manually like this:

element.style.width = element.offsetWidth + 'px';

Check out this code example on my website!

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

Which comes first in AngularJS: ng-include or ng-repeat?

What is the outcome if I have a template containing ng-repeat and include it using ng-include? Will the included template have the completed ng-repeat, or will it be included without the ng-repeat being complete (and then completed after inclusion)? ...

The HTTP request is being executed twice for some reason unknown to me

import React, {useState, useEffect} from 'react' export function UseStateExample() { // This is a named export that must be used consistently with {} when importing/exporting. const [resourceType, setResourceType] = useState(null) useEffect ...

Using jQuery to load content into a jQuery UI dialog box

I am looking to implement a pop-up that displays content from another asp page. To achieve this, I am using jquery.load to load the page into a div and jquery-ui.dialog. This is my code: <div id="dialog"></div> Inside the document ready fun ...

Ways to identify input that has been altered dynamically

I'm currently trying to figure out why I can't seem to detect any input changes with the code snippet below: $("#fname").on("change", function () { console.log("The text has been changed."); }); $("button").o ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

Authorization based on user roles in Node.js or Express.js

Are there any modules available for implementing role-based authorization in node.js or Express js? For example, having roles such as Super Admin, Admin, Editor, and User? ...

Different ways to dynamically change tailwind colors during execution

Utilizing tailwind v3, it's feasible to customize existing colors by modifying the tailwind.config file. https://tailwindcss.com/docs/customizing-colors module.exports = { theme: { extend: { colors: { gray: { ...

When attempting to use Arabic characters in my PDF file with LIP, I encounter an error: "TypeError: font must be of type PDFFont or n, but was actually of type NaN"

all I am facing an issue with Arabic characters when trying to use different fonts in my project. I have attempted to encode the Arabic letters using various npm packages, but I keep receiving a TypeError: font must be of type PDFFont or n but was actuall ...

What is preventing me from using jQuery to dynamically insert HTML onto the page?

Below is the HTML code for a Bootstrap Modal dialog box: <div class="modal fade" id="rebateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> ...

Trouble opening attached html file with Asp.net and Google Charts integration

I am facing an issue with my Asp.Net page that includes a grid and an image. The image is a Google Charts chart with a URL of approximately 1600 characters. To send this content as an email attachment, I created an .htm file containing the grid and the ima ...

BlurDataURL for Data URLs in Next.js

NextJS 11 brings the exciting feature of using the Image component with a blur placeholder. To utilize this with dynamic images, we need to make use of the blurDataURL, which is a Data URL. I am interested in taking my original image and resizing it to a ...

Tips on creating animations for a background with a value of 2 using CSS3

Hey everyone, I'm currently working with this CSS style: body { width:100%; height:100%; background:#fff; background-image: url(bg.png), url(clouds.png); background-repeat: repeat; font-family: tahoma; font-size: 14px; ...

Issue found in factory and service dependencies

To retrieve user information, the factory sends a request to the API using ApiRequest.sendRequest: (function() { angular.module('isApp.user', []) .factory('UserProfileFactory', function( $log, ApiRequest, dataUrls ) { // User pr ...

What could be the reason for receiving a Firebase INVALID_DYNAMIC_LINK_DOMAIN error message?

I'm having trouble implementing email verification in my React website. Whenever I use the sendSignInLinkToEmail function, I encounter the following error: XHRPOSThttps://identitytoolkit.googleapis.com/v1/accounts:sendOobCode?key=xxxxxxxxxxxxxxxxxxx [ ...

What is the optimal parameter order when utilizing pre-curried functions and composition in JavaScript?

We have a simple, mathematically curried function for subtracting numbers: function sub(x) { return function (y) { return x - y; }; }; sub(3)(2); // 1 The function signature matches the obtained result. However, when function composition comes i ...

Pictures displaying various shapes in contact with each other

I have a unique challenge involving an image that has been physically cut into puzzle-shaped pieces. Is there a way to align these individual puzzle pieces using only HTML and CSS to create the illusion of a single cohesive image once assembled? It' ...

What is the best way to integrate a Vue component into a Knockout application?

My webpage is filled with knockout code, but I'm hoping to integrate a Vue.js component for a specific section. I attempted using controlsDescendantBindings on a surrounding tag for the Vue component, and it seems to be partially functional (I tried ...

Populate the AngularJS scope with a dynamically generated array

My Angular Application is functioning properly with <script> var app = angular.module('MyApp', []); app.controller('myCtrl', function ($scope, $sce) { $scope.urls = [ { "url": $sce.t ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

My div is currently being concealed by a jQuery script that is hiding all of its

Below is the current code snippet: jQuery(document).ready(function($) { $("ul.accordion-section-content li[id*='layers-builder'] button.add-new-widget").click(function() { $("#available-widgets-list div:not([id*='layers-widget']) ...