We've been creating an interactive experiences that leverages the mousemove event this week. It's the same project mentioned in the Interactive Swarm script. Take a look if you haven't (https://slater-original.webflow.io/swarm) and then let's run through a more basic example that can illustrate how to make an interactive expereince with the mousemove event.
For this example, let's create a simple game where you can move a box around the screen with your mouse!
First, we'll start with some basic HTML:
<div id="box"></div>
And add a bit of CSS to make it visible:
#box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
Now for the fun part - the JavaScript:
// Get our box
let box = document.getElementById('box');
// Listen for mouse movement on the whole page
document.addEventListener('mousemove', function(e) {
// Move the box to where the mouse is
box.style.left = e.clientX + 'px';
box.style.top = e.clientY + 'px';
});
Here's what this code does:
- We find our box using document.getElementById('box').
- We tell the computer to listen for when the mouse moves anywhere on the page.
- When the mouse moves, we run a function that:
- Sets the box's left position to where the mouse is horizontally (e.clientX)
- Sets the box's top position to where the mouse is vertically (e.clientY)
The e in function(e) is like a package of information about the mouse movement (try logging it to the console). e.clientX tells us how far right the mouse is, and e.clientY tells us how far down it is. We add 'px' at the end because CSS needs to know we're talking about pixels.
And that's it! Now when you move your mouse around the page, the red box will follow it.