Tiny Draggable & Resizable Library – resizedrag.js

Category: Drag & Drop , Javascript | July 27, 2021
Author:MurugappanVR
Views Total:93 views
Official Page:Go to website
Last Update:July 27, 2021
License:MIT

Preview:

Tiny Draggable & Resizable Library – resizedrag.js

Description:

A tiny JavaScript library that makes DOM elements draggable (moveable) and resizable.

How to use it:

1. Install and import the resizedrag.js with NPM.

# NPM
$ npm i resizedrag --save

import { resizedrag } from 'resizedrag';

2. Initialize the resizedrag.js on the target DOM element and config the draggable and resizable behaviors using the following data attributes:

  • data-rd-drag-enabled: Enable draggable. Default: true.
  • data-rd-min-height: Min height in pixels. Default: 5.
  • data-rd-min-width: Max height in pixels. Default: 5.
  • data-rd-drag-border-enabled: Show border when being dragged. Default: true.
<div class="drag-widget-container" 
     id="example" 
     data-rd-drag-enabled="false" 
     data-rd-min-height=25 
     data-rd-min-width=25 
     data-rd-drag-border-enabled="false"
     >
</div>
// resizedrag(target, handler, onStart, onEnd);
resizedrag(document.querySelector("#example"),document.querySelector("#example"));

3. Use the start/end events to simulate “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) {
  console.log('end');
  // 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"
  }
}
resizedrag(document.querySelector("#example"),document.querySelector("#example"), onStart, onEnd);

You Might Be Interested In:


One thought on “Tiny Draggable & Resizable Library – resizedrag.js

  1. C C

    Recommend that you adjust the “let targetElement = document.getElementById (target.id);” line in resizedrag.js by “let targetElement = target”;
    In your version
    1) the code works only for elements which have an id attribute and
    2) the code works only when an element has already been made part of the DOM of the document.
    Both aspects cannot be taken for granted.

    Reply

Leave a Reply