/    /  Javascript Drag n Drop

Javascript Drag n Drop

 

Drag and drop is a common user interaction that we can find in many graphical user interfaces(UI).

There are pre-existing JavaScript libraries for adding a drag-and-drop feature to your app(website). However, there may be situations where a library does not provide (not available) or introduces an overhead (or dependency that your project does not need). In these situations, knowledge of the APIs available or provide to you in modern web browsers(websites) can offer alternative solutions.

The HTML Drag and Drop API relies on the DOM’s event model to get information on what is being dragged or dropped and to update that HTML element on drag or drop. With JavaScript event, handlers, we can turn any HTML element into a draggable item or an item that can be dropped into.

 

Example:

 

HTML:

<div id="drag-1" class="draggable">
 <p> You can drag one element </p>
</div>
<div id="drag-2" class="draggable">
 <p> with each pointer </p>
</div>

CSS:

#drag-1, #drag-2 {
 width: 25%;
 min-height: 6.5em;
 margin: 1rem 0 0 1rem;
 background-color: #29e;
 color: white;
 border-radius: 0.75em;
 padding: 4%;
 touch-action: none;
 user-select: none;
 -webkit-transform: translate(0px, 0px);
     transform: translate(0px, 0px);

JAVASCRIPT:

// target elements with the "draggable" class
interact('.draggable')
 .draggable({
  // enable inertial throwing
  inertia: true,
  // keep the element within the area of it's parent
  modifiers: [
   interact.modifiers.restrictRect({
     restriction: 'parent',
     endOnly: true
   })
  ],
  // enable autoScroll
  autoScroll: true,

  listeners: {
    // call this function on every dragmove event
    move: dragMoveListener,

    // call this function on every dragend event
    end (event) {
     var textEl = event.target.querySelector('p')

     textEl && (textEl.textContent =
      'moved a distance of ' +
      (Math.sqrt(Math.pow(event.pageX - event.x0, 2) +
           Math.pow(event.pageY - event.y0, 2) | 0))
       .toFixed(2) + 'px')
    }
   }
 })

function dragMoveListener (event) {
 var target = event.target
 // keep the dragged position in the data-x/data-y attributes
 var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
 var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy

 // translate the element
 target.style.webkitTransform =
  target.style.transform =
   'translate(' + x + 'px, ' + y + 'px)'

 // update the posiion attributes
 target.setAttribute('data-x', x)
 target.setAttribute('data-y', y)
}

// this function is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener

 

OUTPUT:

 

Javascript Drag n Drop