How to create a draggable HTML element with JavaScript and CSS?

JavascriptWeb DevelopmentObject Oriented Programming

To create a draggable HTML element with JavaScript and CSS, the code is as follows −

Example

 Live Demo

<!DOCTYPE html>
<html>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .dragDiv {
      position: absolute;
      z-index: 9;
      text-align: center;
      border: 1px solid #d3d3d3;
      padding: 30px;
      cursor: move;
      z-index: 10;
      background-color: rgb(108, 24, 177);
      color: #fff;
      font-size: 20px;
      font-weight: 500;
   }
</style>
<body>
<h1>Draggable DIV Element Example</h1>
<h2>Click and drag the below element to move it around</h2>
<div class="dragDiv">
This div can be moved around
</div>
<script>
   dragElement(document.querySelector(".dragDiv"));
   function dragElement(ele) {
      var pos1 = 0,
      pos2 = 0,
      pos3 = 0,
      pos4 = 0;
      if (document.querySelector(ele.id + "header")) {
         document.getElementById(
            ele.id + "header"
         ).onmousedown = dragMouseDown;
      }
      else {
         ele.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;
         ele.style.top = ele.offsetTop - pos2 + "px";
         ele.style.left = ele.offsetLeft - pos1 + "px";
      }
      function closeDragElement() {
         document.onmouseup = null;
         document.onmousemove = null;
      }
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On moving the div around by dragging −

raja
Published on 12-May-2020 12:17:09
Advertisements