A Super Tiny Javascript Library to Make Dom Elements Draggable and Movable

A tiny drag and drop library that makes any DOM element draggable by clicking the drag the handle and holding the mouse.

How to use it:

  1. Install the dragmove.js package with NPM.
## NPM
$ npm i @knadh/dragmove --save
  1. Import the dragmove.js as an ES module.
import { dragmove } from @knadh/dragmove;

3. Add a drag handle to the element.

<div id="example">
  <div class="handle">Drag here</div>
</div>
  1. Apply the drag and drop functionality to the element.

dragmove(document.querySelector(“#example”), document.querySelector(“#example .handle”))

5. Make the draggable element move within the boundaries of the viewport.

<div id="example" data-drag-bound="true">
  <div class="handle">Drag here</div>
</div>

6. Use the start/end events to simulate a “snap to edge” behaviour.

const snapThreshold = 50;
function onStart(el, x, y) {
  // On drag start, remove the fixed bottom style to prevent the bottom
  // from sticking on the screen.
  el.style.top = el.offsetTop + "px"
  el.style.bottom = "auto"
}
function onEnd(el, x, y) {
  // Automatically snap to corners.
  if (window.innerHeight - (el.offsetTop + el.offsetHeight) < snapThreshold) {
      el.style.top = "auto"
      el.style.bottom = "0px"
  }
  if (window.innerWidth - (el.offsetLeft + el.offsetWidth) < snapThreshold) {
      el.style.left = "auto"
      el.style.right = "0px"
  }
  if (el.offsetTop < snapThreshold) {
      el.style.top = "0px"
  }
  if (el.offsetLeft < snapThreshold) {
      el.style.left = "0px"
  }
}
dragmove(document.querySelector("#example"), document.querySelector("#example .handle"), onStart, onEnd)

Download Details:

Author: knadh

Demo: https://knadh.github.io/dragmove.js/docs/

Source Code: https://github.com/knadh/dragmove.js

#javascript

A Super Tiny Javascript Library to Make Dom Elements Draggable and Movable
2.80 GEEK