Create Draggable Elements With Snapping In jQuery - magnet.js

File Size: 63.3 KB
Views Total: 1870
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Create Draggable Elements With Snapping In jQuery - magnet.js

This is the jQuery version of the Magnet.js library which lets you create draggable elements with support for auto snapping on move.

How to use it:

1. Download and place the jquery-magnet.min.js script after the latest jQuery library.

<script src="/path/to/cdn/jquery.min.js"></script>
<script src="/path/to/jquery-magnet.min.js"></script>

2. Initialize the Magnet.js plugin with optional settings. All possible settings:

  • distance: distance for elements to attract others in the same group
  • attractable: makes elements attractable
  • allowCtrlKey: allows CTRL key to make elements unattractable
  • allowDrag: allows draggable
  • useRelativeUnit: whether or not to use relative unit
  • stayInParent: makes all elements stay in the parent container
  • alignOuter: aligns outer edges
  • alignInner: aligns inner edges
  • alignCenter: centers elements to others
  • alignParentCenter: centers elements to the parent container
let $magnet = $.magnet({
    // options and defaults
    distance: 0,
    attractable: true,
    allowCtrlKey: true,
    allowDrag: true,
    useRelativeUnit: false,
    stayInParent: false,
    alignOuter: true,
    alignInner: true,
    alignCenter: true,
    alignParentCenter: false
});

3. Add elements to the group.

$magnet.add('.magnet');

4. Remove elements from the group.

$magnet.remove('.magnet');
$magnet.removeFull('.magnet');
$magnet.clear();
$magnet.clearFull();

5. You can also adjust the settings by using the following API methods.

// distance
$magnet.distance(3);

// attractable
$magnet.attractable(); // get
$magnet.attractable(true); // set

// allows CTRL key
$magnet.allowCtrlKey(); // get
$magnet.allowCtrlKey(true); // set

// allows draggable
$magnet.allowDrag(); // get
$magnet.allowDrag(true); // set

// whether or not to use relative unit
$magnet.useRelativeUnit(); // get
$magnet.useRelativeUnit(true); // set

// sets/gets aligments
$magnet.alignOuter(true);
$magnet.alignInner(false); 
$magnet.alignCenter(true);
$magnet.alignParentCenter(false); 
$magnet.alignOuter(); // get

// makes elements stay in the parent
$magnet.stayInParent(); // get
$magnet.stayInParent(true); // set

// makes elements stay in the parent
$magnet.stayInParent(); // get
$magnet.stayInParent(true); // set

6. Event handlers.

$magnet.on('magnetstart', function(evt) {
  // do something
});

$magnet.on('magnetend', function(evt) {
  // do something
});

$magnet.on('magnetchange', function(evt) {
  // do something
});

Changelog:

v1.0.9 (2022-01-10)

  • Bugfix

2021-09-22

  • Dependency updated

v1.0.8 (2020-04-05)

  • Removed debug log

This awesome jQuery plugin is developed by lf2com. For more Advanced Usages, please check the demo page or visit the official website.