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 and
  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;}
<div id="drag1">Drag me</div>

(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;} = (objInitLeft + e.pageX-dragStartX) + "px"; = (objInitTop + e.pageY-dragStartY) + "px";
  document.addEventListener("mouseup", function(e) {inDrag = false;});
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit


Click here to write/view comments