Skip to content

Instantly share code, notes, and snippets.

@jonurry
Created March 26, 2018 15:23
Show Gist options
  • Save jonurry/753ab13acc8175acc9a402948680163e to your computer and use it in GitHub Desktop.
Save jonurry/753ab13acc8175acc9a402948680163e to your computer and use it in GitHub Desktop.
15.2 Mouse Trail (Eloquent JavaScript Solutions)
<style>
.trail { /* className for the trail elements */
position: absolute;
height: 6px; width: 6px;
border-radius: 3px;
background: teal;
}
body {
height: 300px;
}
</style>
<script>
let dots = [];
let radius = 3;
function addToTrail(x, y) {
let dot = document.createElement('div');
dot.className = 'trail';
dot.style.left = x - radius + 'px';
dot.style.top = y - radius + 'px';
document.body.appendChild(dot);
dots.push(dot);
setTimeout(removeFromTrail, 500);
};
function removeFromTrail() {
document.body.removeChild(dots.shift());
};
function mouseTrail(e) {
addToTrail(e.pageX, e.pageY);
};
document.addEventListener('mousemove', mouseTrail);
</script>
@jonurry
Copy link
Author

jonurry commented Mar 26, 2018

Hints

Creating the elements is best done with a loop. Append them to the document to make them show up. To be able to access them later in order to change their position, you’ll want to store the elements in an array.

Cycling through them can be done by keeping a counter variable and adding 1 to it every time the "mousemove" event fires. The remainder operator (% elements.length) can then be used to get a valid array index to pick the element you want to position during a given event.

Another interesting effect can be achieved by modelling a simple physics system. Use the "mousemove" event only to update a pair of bindings that track the mouse position. Then use requestAnimationFrame to simulate the trailing elements being attracted to the position of the mouse pointer. At every animation step, update their position based on their position relative to the pointer (and, optionally, a speed that is stored for each element). Figuring out a good way to do this is up to you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment