Search code examples
javascriptcss

How do I make an element follow the mouse?


I wanted to make a div follow mouse so I added this code:

const move = document.getElementById("move");

document.body.onpointermove = event => {
    const { clientX, clientY } = event;

    move.animate({
        left: `${clientX}px`,
        top: `${clientY}px`
    
    }, {duration: 1000, fill: "forwards"})

}
#move{
    background: linear-gradient(
        to right,
        #ff8e8e,
        #ff006a
    ) ;
    height: 300px;
    aspect-ratio: 1;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    position: fixed;
}
<div id="move"></div>

At first when I inspected the site in my browser the JS was changing left and top value as I was moving my mouse but it wasn't moving. Because of this, I added this into css position: fixed;. The div started following my mouse but only if it was over it. I wanted the div to always follow the mouse but I don't know how to do it.

I hope that somebody will help me with this.


Solution

  • The problem is simply caused by the fact the body element now has a height of 0 (since setting position: fixed on the div removed it from normal flow and the body no longer reserves space for it). Your cursor is technically outside the body when you move it around the page, so it doesn't fire the pointermove event. But when the cursor is inside the div, which is itself a descendant of the body, it counts as being inside the body.

    You could fix this by attaching the event to the window instead of the body, or by making sure the html and body elements have a minimum height.

    const move = document.getElementById("move");
    
    document.body.onpointermove = event => {
        const { clientX, clientY } = event;
    
        move.animate({
            left: `${clientX}px`,
            top: `${clientY}px`
        
        }, {duration: 1000, fill: "forwards"})
    
    }
    html { height: 100%; }
    body { min-height: 100%; }
    
    #move{
        background: linear-gradient(
            to right,
            #ff8e8e,
            #ff006a
        ) ;
        height: 300px;
        aspect-ratio: 1;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        position: fixed;
    }
    <div id="move"></div>