javascripthtmldrag-and-droptargeting

Drag 'n Drop Element targeting


so i was programming (with a friend) a Drag 'n Drop system with elements (here buttons) for HTML in plain JS. Then i realised, what if i have multiple element on this page? Answer: All these are being affected. So i said... okay! i just increasingly add a value to the id, then the whole thing won't interfere.

So now I've got the Problem, that i can't know which element is being targeted... or better: which id is being targeted.

PS: Please JS only no JQuery and no Frameworks.

PPS: (I already looked through Stackoverflow etc for this situation, nothing very suiting to my case, at least i didn't found one)

    var pressed = 0;

    function drag(state){
        if(state == true){
           pressed = 1;
        }
        else{
           pressed = 0;
        }
    }
  var obj = "";
    onmousemove = function(a){
        if(pressed == 1){
    obj = document.getElementById("move1"); //<-- This var (obj) needs to be "flexible" to any element, not only the element with the id "move1"
            var x = a.clientX - parseInt(obj.style.width) / 2;
            var y = a.clientY - parseInt(obj.style.height) / 2;
            obj.style.left = x + "px";
            obj.style.top = y + "px";
        }
    }

var counter = 0;

function createbutton() {
counter++;
document.getElementById("surface").innerHTML += "<button id = 'move" + counter + "' style = 'width: 100px; height: 100px; background-color: blue; border: none; position: fixed;' onmousedown = 'drag(true)' onmouseup = 'drag(false)' onClick = 'drag(false)'>Move this Button</button>";
}

` Note: This doesn't include HTML because somehow Stackoverflow does not show properly, so only JS, pls visit JSFiddle to see full (create multiple Buttons and drag the last one!): https://jsfiddle.net/2nyc4a83/


Solution

  • I added a new parameter to your function drag(). On the events onmousedown, onmouseup and onClick the id of the current object will be used as an argument for drag(). Example for how this looks in the code: <button ... onmousedown = 'drag(true, this.id)'>Move this button</button>

    The id will then be saved in a global variable so that you can later access it in the onmousemove function like this:

    obj = document.getElementById(obj_id);
    

    -> jsfiddle