Drag And Drop With Snap Into Place – Magnet.js

Category: Drag & Drop , Javascript | July 2, 2018
Author: lf2com
Views Total: 3,264
Official Page: Go to website
Last Update: July 2, 2018
License: MIT

Preview:

Drag And Drop With Snap Into Place – Magnet.js

Description:

Magnet.js is a small and standalone JavaScript library that provides drag and drop with snap into place functionality for single or grouped elements.

How to use it:

Install the Magnet.js via NPM:

# NPM
$ npm install magnet --save

Initialize the Magnet.js library.

let magnet = new Magnet();

Add elements which should be draggable.

<div class="magnet">
  ...
</div>
magnet.add(document.querySelectorAll('.magnet'));

Set the attract distance in pixels.

magnet.distance(30);

Enable/disable alignment types.

magnet.enabledAlignOuter(true);
magnet.enabledAlignInner(true); 
magnet.enabledAlignCenter(true);

If you want to keep the draggable element in the parent element.

magnet.stayInParentEdge(true);

Remove elements.

magnet.remove(document.querySelector('.magnet'));

Clear the element group.

magnet.clear();

Event handlers.

magnet.on('magnetenter', function(e) {
  console.log('magnetenter', e.detail); 
});

magnet.on('magnetleave', function(e) {
  console.log('magnetleave');
});

magnet.off('magnetenter magnetleave');

elem.addEventListener('attract', function(e) {
  console.log('attract', e.detail); 
});

elem.addEventListener('unattract', function(e) {
  console.log('unattract');
});

elem.addEventListener('attracted', function(e) {
  console.log('attracted', e.detail); 
});

elem.addEventListener('unattracted', function(e) {
  console.log('unattracted');
});

Changelog:

07/03/2018

  • Sync methods: stayInParentEdge and stayInParentElem

06/02/2018

  • Fixed remove function

You Might Be Interested In:


One thought on “Drag And Drop With Snap Into Place – Magnet.js

Leave a Reply