Javascript event handler mousedown and mousemove can be used to make an element draggable without using any other library. This can be made to work on mobile also using touchstart and touchmove. For the purpose of this example, we’ll only focus on desktop.
Here is the overflow code flow:
- The element which we want to make draggable should be positioned element (relative, absolute or fixed).
- Store element page position on mousedown using element.offsetLeft and element.offsetTop
- Store click event’s page position on mousedown using event.pageX and event.pageY. Note that this will be slightly different from element’s position depending upon where did use click within element.
- Change state inDrag to true on mousedown
- onmousemove, change element’s position using element.style.left and element.style.top.
- onmouseup set state inDrag=false.
- Note that mousemove and mouseup are attached to document. This will handle the case of user moving mouse too fast.
<style type="text/css"> #drag1 {position:relative; width:100px; background-color: lightblue;} </style> <div id="drag1">Drag me</div> <script> (function(elementSelector) { var dragStartX, dragStartY; var objInitLeft, objInitTop; var inDrag = false; var dragTarget = document.querySelector(elementSelector); dragTarget.addEventListener("mousedown", function(e) { inDrag = true; objInitLeft = dragTarget.offsetLeft; objInitTop = dragTarget.offsetTop; dragStartX = e.pageX; dragStartY = e.pageY; }); document.addEventListener("mousemove", function(e) { if (!inDrag) {return;} dragTarget.style.left = (objInitLeft + e.pageX-dragStartX) + "px"; dragTarget.style.top = (objInitTop + e.pageY-dragStartY) + "px"; }); document.addEventListener("mouseup", function(e) {inDrag = false;}); }("#drag1")) </script>