How To Create Moving Element Based On Cursor

In this article, we learn how to create moving elements based on the cursor.
Step 1: Create an element and apply CSS.

<!DOCTYPE html>
<html>
    <head>
        <title>
            Create Moving Element
        </title>
        <style>
            #myElement{
                width: 10px;
                height: 10px;
                border-radius: 50px;
                background-color: violet;
                position: fixed;
            }
        </style>
    </head>
    <body>
        <div id="myElement">
        </div>
    </body>
</html>
Step 2: Apply the below javascript to get cursor potion and apply position into created element.
var pointerX = -1;
var pointerY = -1;
document.onmousemove = function(event) {
    pointerX = event.pageX;
    pointerY = event.pageY;
    pointer = document.querySelector('#myElement');
    width = pointer.offsetWidth/2;
    height = pointer.offsetHeight/2;
    document.getElementById("myElement").style.top=(pointerY-height)+"px";
    document.getElementById("myElement").style.left=(pointerX-width)+"px";
}
Step 3: Add “pointer-events: none;” CSS to make element unselectable.
#myElement{
    pointer-events: none;
    position: fixed;
    width: 10px;
    height: 10px;
    border-radius: 50px;
    background-color: violet;
}

Here is the full code:

<!DOCTYPE html>
<html>
    <head>
        <title>
            Create Moving Element
        </title>
        <style>
            #myElement{
                pointer-events: none;
                position: fixed;
                width: 10px;
                height: 10px;
                border-radius: 50px;
                background-color: violet;
            }
        </style>
    </head>
    <body>
        <div id="myElement" style="">
        </div>
        <div class="test">
            This is testing page.
        </div>
    </body>
    <script>
        var pointerX = -1;
        var pointerY = -1;
        document.onmousemove = function(event) {
            pointerX = event.pageX;
            pointerY = event.pageY;
            pointer = document.querySelector('#myElement');
            width = pointer.offsetWidth/2;
            height = pointer.offsetHeight/2;
            document.getElementById("myElement").style.top=(pointerY-height)+"px";
            document.getElementById("myElement").style.left=(pointerX-width)+"px";
        }
    </script>
</html>
Here is the result:
Thanks.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories