Languages
[Edit]
EN

JavaScript - how to make drag and drop div?

5 points
Created by:
Root-ssh
6357

Using JavaScript it is possible to make drag&drop div element in following way.

1. Custiom solution example

Note: big advantage of presented approach in this section is resistance for changed margin, border and padding sizes (with nested elements too).

More complicated example with handle element is here.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div.draggable {
        padding: 10px;
        position: absolute;
        left: 20px; right: 20px;
        background: gray;
        width: 150px; height: 150px;
    }

    * { /* this style disables selection for all elements on web page */
        -webkit-touch-callout: none; /* iOS Safari                         */
          -webkit-user-select: none; /* Safari                             */
           -khtml-user-select: none; /* Konqueror HTML                     */
             -moz-user-select: none; /* Firefox in the past (old versions) */
              -ms-user-select: none; /* Internet Explorer (>=10) / Edge    */
                  user-select: none; /* Currently supported:               */
                                     /* Chrome, Opera and Firefox          */
    }

  </style>
  <script type="text/javascript">

    function getMargins(element) {
		var style = element.currentStyle || window.getComputedStyle(element);

        var result = {
            getX: function() {
                return parseInt(style.marginLeft);
            },
            getY: function() {
                return parseInt(style.marginTop);
            }
        };
		
        return result;
    }

    function prepareDragging(element) {
        var dragging = false;

        var clickX, clickY;
        var positionX, positionY;

        var style = element.style;

        function onMouseDown(e) {
            clickX = e.clientX;
            clickY = e.clientY;

            var margins = getMargins(element);

          	// this approach prevents agains different margin sizes
            positionX = element.offsetLeft - margins.getX();
            positionY = element.offsetTop - margins.getY();

            dragging = true;
        }

        function onMouseUp(e) {
            dragging = false;
        }
      
        function onMouseMove(e) {
            if (dragging) {
                var x = positionX + e.clientX - clickX;
                var y = positionY + e.clientY - clickY;
                
                style.left = x + 'px';
                style.top = y + 'px';
            }
        }

        element.addEventListener('mousedown', onMouseDown);  
        window.addEventListener('mouseup', onMouseUp);  
        window.addEventListener('mousemove', onMouseMove);
        
        var remove = function() {
            if (remove) {
                element.removeEventListener('mousedown', onMouseDown);  
                window.removeEventListener('mouseup', onMouseUp); 
                window.removeEventListener('mousemove', onMouseMove);

                remove = null;
            }
        };
      
        return remove;
    }

  </script>
</head>
<body style="height: 200px;">
  <div id="my-element" class="draggable">
     Something inside...
  </div>
  <script>

      var element = document.querySelector('#my-element');

      prepareDragging(element);

  </script>
</body>
</html>

See also

  1. HTML - how to disable text selection?
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.