How to create draggable HTML elements

Learn how to create draggable HTML elements using JavaScript and CSS.

Draggable DIV element

Click here to drag

Move

This

DIV

Create a draggable DIV element

Step 1 - Add HTML:

<!-- Draggable DIV -->
<div id="mydiv">
  <!-- Contains a title DIV with the same name as the draggable DIV, followed by "header" -->
  <div id="mydivheader">Click here to drag</div>
  <p>Move</p>
  <p>This</p>
  <p>DIV</p>
</div>

Step 2 - Add CSS:

The only important style is position: absolute;The rest is up to you:

#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
}
#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}

Step 3 - Add JavaScript:

// Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // If the title exists, it is the position you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  }
    // Otherwise, move the DIV from any position inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }
  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // Get the position of the mouse cursor at the start:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // Call the function each time the cursor moves: 
    document.onmousemove = elementDrag;
  }
  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // Calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // Set the new position of the element:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }
  function closeDragElement() {
    // Stop moving when the mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

Try it yourself