Skip to content
Search

HTML:Drag

lastmod 2021-09-02created 2021-08-308 edits

Libraries

Drag and drop events

When you drag an object with the mouse until you drop it, several stages of events fire in sequence.

The following table shows, in order, the events that occur during drag and drop.

Event

Description

dragstart

Fires when the user starts to drag an object.

dragenter

Fires when the mouse first enters over the target object.

dragover

Fires while dragging when the mouse is positioned over the target object.

drag

Fires when the mouse moves while dragging the target object.

drop

Fires on the object at the location where the dragged object is dropped when the drag ends.

dragleave

Fires when the drag ends and the mouse leaves the area over the target object.

dragend

Fires the moment the mouse button is released while dragging the target object.

DataTransfer object

Every event listener method for drag and drop events returns a DataTransfer object.

The returned DataTransfer object holds information about the drag and drop operation.

draggable attribute

Any element in a web page can be turned into a draggable object using the draggable attribute.

ondragstart attribute

After making it a draggable object, call the setData() method of the DataTransfer object through the ondragstart attribute.

The setData() method sets the data and data type of the dragged target object.

ondragover attribute

The ondragover attribute sets which elements the dragged target object can be dropped onto.

By default, HTML elements cannot be placed on top of other elements.

Therefore, to allow placing on top of another element, you must prevent the default behavior of the element at the drop location.

This can be set up simply by calling the event.preventDefault() method.

ondrop attribute

When you drop the dragged object, a Drop event fires.

You can set the behavior for the Drop event using the ondrop attribute.

Event How to

function dragEnter(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}

Examples

Windows-style window moving (custom implementation)

<div class="window">
  <div class="titlebar">Hello, World!</div>
  <div class="content">
    <p>Window <b>Content!</b></p>
  </div>
</div>
// For each item with a `window` class…
var windows = document.querySelectorAll('.window');
[].forEach.call(windows,function(win){

  // …find the title bar inside it and do something onmousedown
  var title = win.querySelector('.titlebar');
  title.addEventListener('mousedown',function(evt){

    // Record where the window started
    var real = window.getComputedStyle(win),
        winX = parseFloat(real.left),
        winY = parseFloat(real.top);

    // Record where the mouse started
    var mX = evt.clientX,
        mY = evt.clientY;

    // When moving anywhere on the page, drag the window
    // …until the mouse button comes up
    document.body.addEventListener('mousemove',drag,false);
    document.body.addEventListener('mouseup',function(){
      document.body.removeEventListener('mousemove',drag,false);
    },false);

    // Every time the mouse moves, we do the following 
    function drag(evt){
      // Add difference between where the mouse is now
      // versus where it was last to the original positions
      win.style.left = winX + evt.clientX-mX + 'px';
      win.style.top  = winY + evt.clientY-mY + 'px';
    };
  },false);
});
body { background:#eee }
.window {
    position:absolute;
    top:20px; left:30px; width:200px; height:150px;
    border:1px solid #ddd;
    background:#fff;
    box-shadow:3px 3px 10px rgba(0,0,0,0.2);
    user-select:none;
    -webkit-user-select:none;
    -moz-user-select:none;
}
.window .titlebar { background:#ddd; text-align:center; cursor:move; border-bottom:1px solid #ccc }
.window .content { padding:1em }

Excel-style column moving

Moving an element by dragging

<div id="dragMe" class="draggable">Drag me</div>
.draggable {
    /* Indicate the element draggable */
    cursor: move;

    /* It will be positioned absolutely */
    position: absolute;

    /* Doesn't allow to select the content inside */
    user-select: none;
}
// The current position of mouse
let x = 0;
let y = 0;

// Query the element
const ele = document.getElementById('dragMe');

// Handle the mousedown event
// that's triggered when user drags the element
const mouseDownHandler = function(e) {
    // Get the current mouse position
    x = e.clientX;
    y = e.clientY;

    // Attach the listeners to `document`
    document.addEventListener('mousemove', mouseMoveHandler);
    document.addEventListener('mouseup', mouseUpHandler);
};

const mouseMoveHandler = function(e) {
    // How far the mouse has been moved
    const dx = e.clientX - x;
    const dy = e.clientY - y;

    // Set the position of element
    ele.style.top = `${ele.offsetTop + dy}px`; 
    ele.style.left = `${ele.offsetLeft + dx}px`;

    // Reassign the position of mouse
    x = e.clientX;
    y = e.clientY;
};

const mouseUpHandler = function() {
    // Remove the handlers of `mousemove` and `mouseup`
    document.removeEventListener('mousemove', mouseMoveHandler);
    document.removeEventListener('mouseup', mouseUpHandler);
};

ele.addEventListener('mousedown', mouseDownHandler);

See also

Favorite site

author Zer0 sitemap