1

I have this code for creating movable windows (elements), and I call this function when I create a new window:

function dragWindow(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    elmnt.querySelector(".window-caption").onmousedown = dragMouseDown;
    function dragMouseDown(e) {
        e.preventDefault();
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
    }
    function elementDrag(e) {
        e.preventDefault();
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }
    function closeDragElement() {
        // alert(elmnt.id);
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

The problem is:

if I create a new window, I can't move windows they created before.

2 Answers2

0

When you moved up the mouse, function closeDragElement() was called and the event listener document.onmousemove was overwritten to 'null'.

Comment out the last line in function closeDragElement() may solve this problem:

function closeDragElement() {
        // alert(elmnt.id);
        document.onmouseup = null;
        // document.onmousemove = null;
}

Edit: added an variable mousedown to indicate whether the mouse is down.

function dragWindow(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    var mousedown = 0;
    elmnt.querySelector(".window-caption").onmousedown = dragMouseDown;
    function dragMouseDown(e) {
        e.preventDefault();
        mousedown++;
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
    }
    function elementDrag(e) {
        e.preventDefault();
        if (mousedown === 0) {return;}
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }
    function closeDragElement() {
        // alert(elmnt.id);
        mousedown--;
        document.onmouseup = null;
        //document.onmousemove = null;
    }
}

Reference: https://stackoverflow.com/a/322827/8031896

zhugen
  • 240
  • 3
  • 11
  • oh this makes another problem, after mouseup window still moves with mouse move. –  Mar 20 '20 at 19:56
  • @A.L. Oh, didn't see that coming. The edited version introduced an additional variable to record the mousedown status. Hopefully this will work. – zhugen Mar 20 '20 at 20:23
0

I called the function again on each of the windows (in developer console); And it showed me the right answer:

So, when I create a new window, I should call dragWindow again for each window.