how to make multiple movable elements

104 Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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.

2
On

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