Magnet-mouse.js is a JavaScript animation library which allows DOM elements to follow the mouse with many parameters.
It works with DOM attributes, JavaScript Objects and CSS properties.
Getting started | Documentation | Demos and examples
Via npm
npm install fluffy-factory/magnet-mouse --save
Via CDN
<script src="https://cdn.jsdelivr.net/gh/fluffy-factory/magnet-mouse@latest/lib/magnet-mouse.min.js"></script>
or manual download.
3 possibilities to install the plugin :
- import
- require
- or by file include
import MagnetMouse from 'magnet-mouse';
const magnetMouse = require('magnet-mouse');
Link magnet-mouse.min.js
in your HTML :
<script src="magnet-mouse.min.js"></script>
let mm = new MagnetMouse({
magnet: {
element: '.magnet'
}
});
mm.init();
For the transition of the element when the cursor hovers it, you must add CSS:
.magnet {
transition: transform .3s ease;
}
{
magnet: {
element: '.magnet-mouse', /* Element to magnet */
class: 'magnet-mouse-active', /* Adds a class when the magnet effect begins */
enabled: true, /* Enables the magnet effect */
distance: 20, /* Distance (in px) when the magnet effect around element activates */
position: 'center' /* Position of mouse relative to the element when magnet effect is active */
},
follow: {
element: '.follow-mouse', /* Element that follows the mouse */
class: 'follow-mouse-active' /* Add class to element that follows the mouse when enter in the magnet effect */
},
throttle: 10, /* Time (in ms) between each eventListener calls */
inCallback: null, /* Callback when mouse enters in the magnet effect */
outCallback: null /* Callback when mouse leaves in the magnet effect */
}
For position, you have multiple choices :
position: 'center' /* center by default, top-left, top-right, bottom-left, bottom-right, top-center, bottom-center */
When using callbacks, the target element's properties are accessible:
let mm = new MagnetMouse({
magnet: {
element: '.magnet'
},
inCallback: function (data) {
console.log(data);
}
});
Result returns:
{
elem: {
height: 58, /* Height of the element (in px) */
width: 126.65625, /* Width of the element (in px) */
node: 'div.magnet.one' /* Node of the element */
},
xMax: 1106.65625, /* Right position of the element */
xMin: 940, /* Left position of the element */
yMax: 194, /* Bottom position of the element */
yMin: 96 /* Top position of the element */
}
Initializes Magnet mouse
mm.init();
Returns the position of each element (same json above)
mm.getElementsPosition();
Returns the mouse's position (posX and posY)
mm.getMousePosition(window.event);
Destroys a Magnet mouse (Removes eventListener and CSS classes)
mm.destroy();
On mobile and tablets there is no mouse, so the plugin is automatically disabled on these platforms.
Website | MIT License | © 2019 Fluffy Factory