Easy way to create draggable div using javascript

Hello guys in this tutorial we will create an draggable div using javascript

First we need to create two files index.html and style.css then we need to do code for it.

Step:1

Add below code inside index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Draggable Element</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans&display=swap" rel="stylesheet">
</head>
<body>
  <div id="draggable-colmun">
    <div class="content">
      <div id="draggableheader">Click here to move</div>
      <h1>Stackfindover</h1>
      <p>Stack Findover is the largest, most trusted online community for developers to learn, share​ ​their programming ​knowledge, and build their careers.</p>
    </div>
  </div>
  <script type="text/javascript">
    dragElement(document.getElementById("draggable-colmun"));
    function dragElement(element) {
      var pos1 = 0,pos2 = 0,pos3 = 0,pos4 = 0;
      if (document.getElementById(element.id + "header")) {
        document.getElementById(element.id + "header").onmousedown = dragMouseDown;
      }else {
        element.onmousedown = dragMouseDown
      }
      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();

        pos3 = e.clientX;
        pos4 = e.clientY;

        document.onmouseup = closeDragElement;

        document.onmousemove = elementDrag;

      }

      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();

        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;

        element.style.top = (element.offsetTop - pos2) + "px";
        element.style.left = (element.offsetLeft - pos1) + "px";
      }

      function closeDragElement() {
        document.onmouseup = 0;
        document.onmousemove = 0;
      }
    }
  </script>
</body>
</html>

Step:2

Then we need to add code for style.css which code i provide in below screen.

*{
  padding: 0;
  margin: 0;
  font-family: 'IBM Plex Sans', sans-serif;
}
body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
} 
div#draggable-colmun .content {
    max-width: 320px;
}
div#draggableheader {
    padding: 10px;
    cursor: move;
    z-index: 10;
    background: #2196f3;
    color: #fff;
}
div#draggable-colmun {
    z-index: 99;
    background: #f1f1f1;
    padding: 10px;
    border: 1px solid #2196f3;
    position: absolute;
}

Output:

1 thought on “Easy way to create draggable div using javascript”

Leave a Comment