when mouse in element animate from mouse position onward in javascript

To animate an element in javascript from the mouse position onward, you can add a mousemove event listener to the element and update its position with each movement of the mouse using CSS. Here's an example code snippet:

index.tsx
const element = document.querySelector('.my-element');
element.addEventListener('mousemove', (e) => {
   element.style.setProperty('--x', e.clientX + 'px');
   element.style.setProperty('--y', e.clientY + 'px');
});
216 chars
6 lines

This code listens for a mousemove event on an element with the class "my-element". In the callback function, it updates the element's position by setting its custom CSS properties "--x" and "--y" to the coordinates of the mouse pointer. You can then use these properties to animate the element's position.

Here is the corresponding CSS code to animate the element's position using the custom properties:

.my-element {
  position: relative;
  --x: 0;
  --y: 0;
  transition: transform .3s ease-out;
}

.my-element:hover {
  transform: translate(var(--x), var(--y));
}
163 chars
11 lines

This CSS uses the variables we set in the javascript to translate the element's position on hover. This creates a smooth animation from the mouse position to the element.

gistlibby LogSnag