Hello everyone this is my first question so I might have done it wrong.
What I am trying to achieve is is have multiple elements all with the same
Don't know if you want to use Jquery or not, but I know it's way simpler than the raw javascript solution. I've been searching the internet and Stack Overflow for a simple drag-and-drop anywhere on a web page solution, but I couldn't find one that worked. The other answers to this question have been weird for me. They sometimes work, sometimes don't. However, a friend suggested using the Jquery version, and wow, it's so much simpler. Just one line of code!
var dragme = document.getElementsByClassName("dragme");
for (var i = 0; i < dragme.length; i++) {
$(dragme[i]).draggable();
}
.dragme {
cursor: move;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<h1 class="dragme">Try dragging me anywhere on this sample!</h1>
<h2 class="dragme">Drag me, too!</h2>
IMPORTANT NOTE: This code does not work with just Jquery, it also requires the Jquery UI file.
If the above sample does not work for you, please comment the error it show below. Note that this works for an unlimited amount of elements. This specific example is for elements with the class "dragme", so just replace that with your own class. For one element, it is a single line of code: $("#yourid").draggable();
.
This code works for me on Google Chrome. Hope this helps anyone coming on to this page late, like me!
The following code will allow drag and drop; I'm sorry it doesn't follow your previous coding style.
Here is a JSFiddle showing it in action: https://jsfiddle.net/6gq7u8Lc/
document.getElementById("dragme").onmousedown = function(e) {
this.prevX = e.clientX;
this.prevY = e.clientY;
this.mouseDown = true;
}
document.getElementById("dragme").onmousemove = function(e) {
if(this.mouseDown) {
this.style.left = (Number(this.style.left.substring(0, this.style.left.length-2)) + (e.clientX - this.prevX)) + "px";
this.style.top = (Number(this.style.top.substring(0, this.style.top.length-2)) + (e.clientY - this.prevY)) + "px";
}
this.prevX = e.clientX;
this.prevY = e.clientY;
}
document.getElementById("dragme").onmouseup = function() {
this.mouseDown = false;
}
On a side note, you won't be able to give them all the same id. The DOM doesn't support such a thing. If you want to add multiple elements of the same type, I would suggest a 'container' parent div, adding the elements as children of the div, and iterating through the .children attribute to access each.