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