I have a draggable div
that works fine as long as I don't alter its position via top, right, …
CSS. My goal is to set the pre-drag position of the div toward the top-right of its window, which I accomplish with top = 0, right = 0
; problem is, the div
sticks to that position and stretches when dragging.
dragElement(document.getElementById("myModal"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;}
else {elmnt.onmousedown = dragMouseDown;}
function dragMouseDown(w) {
w = w || window.event;
w.preventDefault();
pos3 = w.clientX;
pos4 = w.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;}
function elementDrag(w) {
w = w || window.event;
w.preventDefault();
pos1 = pos3 - w.clientX;
pos2 = pos4 - w.clientY;
pos3 = w.clientX;
pos4 = w.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;}}
#myModal {
position: absolute;
z-index: 9;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
top: 0;
right: 0;}
#myModalheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;}
<div id="myModal">
<div id="myModalheader">Click here to move</div>
<p>Move</p><p>this</p><p>DIV</p>
</div>
Any workarounds? Help is appreciated.
Give the element a width and height and you should be good.
dragElement(document.getElementById("myModal"));
function dragElement(elmnt) {
var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
if (document.getElementById(elmnt.id + "header")) {
document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;}
else {elmnt.onmousedown = dragMouseDown;}
function dragMouseDown(w) {
w = w || window.event;
w.preventDefault();
pos3 = w.clientX;
pos4 = w.clientY;
document.onmouseup = closeDragElement;
document.onmousemove = elementDrag;}
function elementDrag(w) {
w = w || window.event;
w.preventDefault();
pos1 = pos3 - w.clientX;
pos2 = pos4 - w.clientY;
pos3 = w.clientX;
pos4 = w.clientY;
elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";}
function closeDragElement() {
document.onmouseup = null;
document.onmousemove = null;}}
#myModal {
position: absolute;
z-index: 9; height: 200px; width: 200px;
background-color: #f1f1f1;
text-align: center;
border: 1px solid #d3d3d3;
top: 0;
right: 0;}
#myModalheader {
padding: 10px;
cursor: move;
z-index: 10;
background-color: #2196F3;
color: #fff;}
<div id="myModal">
<div id="myModalheader">Click here to move</div>
<p>Move</p><p>this</p><p>DIV</p>
</div>