Make an element draggable using Vanilla Javascript

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:

  1. The element which we want to make draggable should be positioned element (relative, absolute or fixed).
  2. Store element page position on mousedown using element.offsetLeft and element.offsetTop
  3. 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.
  4. Change state inDrag to true on mousedown
  5. onmousemove, change element’s position using element.style.left and element.style.top.
  6. onmouseup set state inDrag=false.
  7. 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>
refresh
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments