displaceable
A tiny JavaScript library that handles super smooth element displacement on mouse move. Inspired by this shot.
Demo and code examples
Live demo and React implementation example.
Setup
Install:
npm install displaceable
Basic usage
Import:
import Displaceable from 'displaceable';
Initialize:
// single Node
const displaceable = new Displaceable(document.getElementById('id'));
or
// NodeList
const displaceable = new Displaceable(document.querySelectorAll('img'));
or
// array of Nodes
const displaceable = new Displaceable([
document.getElementById('id-1'),
document.getElementById('id-2'),
document.getElementById('id-3')
]);
Configuration
settings
object
You can pass an object as the second parameter of Displaceable()
to modify the settings of the current instance.
const displaceable = new Displaceable(document.getElementById('id'), {
displaceFactor: 3, // how much the nodes translate on mouse move (float)
lockX: true, // lock movement on the X axis (boolean)
lockY: false, // lock movement on the Y axis (boolean)
resetTime: 1000, // how much it takes the nodes to reset when the mouse leaves the trigger area (ms)
skewFactor: 5, // how much the nodes skew on mouse move (float)
trigger: window // the element that responds to the on mouse move event (window or Node)
});
Data attributes:
data-displace-factor
data-lock-x
data-lock-y
data-skew-factor
To control each Node independently, use the following data attributes. The value set in the data attribute will override the one in the configuration object only for that particular element.
<img
data-displace-factor="10"
data-skew-factor="10"
id="example-id"
/>
<div
data-lock-x="true"
id="example-id"
/>