Skip to content

Instantly share code, notes, and snippets.

@niklasp
Created March 27, 2021 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niklasp/b751f05efcfc0859a6bb796eaa2c38a1 to your computer and use it in GitHub Desktop.
Save niklasp/b751f05efcfc0859a6bb796eaa2c38a1 to your computer and use it in GitHub Desktop.
/**
*
* @param {DOMElement} container
* @param {DOMElement} element
*
* Make the element follow the mouse when it is over container, with
* a following speed of speed.
*/
export function followMouse( container, element, damping ) {
let mouseX = 0, mouseY = 0, translateX = 0, translateY = 0;
function init() {
initListeners();
rAF();
}
function initListeners() {
container.addEventListener( 'mousemove', handleMouseMove );
}
function handleMouseMove( e ) {
const bounds = e.currentTarget.getBoundingClientRect();
mouseX = e.clientX - bounds.left;
mouseY = e.clientY - bounds.top;
}
function rAF() {
translateX += ( mouseX - translateX ) * damping;
translateY += ( mouseY - translateY ) * damping;
element.style.transform = `translate3d( ${ translateX }px, ${ translateY }px, 0)`;
window.requestAnimationFrame( rAF );
}
init();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment