JSFiddle - React, Tailwind, and code Playground

by Julien Etienne

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Reverse Movement</title>
</head>
<body>
    <div id="movingObject"></div>
</body>
</html>

CSS

body {
            margin: 0;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            height: 100vh;
            background-color: yellow;
        }

        #movingObject {
            width: 50px;
            height: 50px;
            background-color: #3498db;
            position: absolute;
            transition: transform 400ms ease-out;
        }

JavaScript

document.addEventListener('DOMContentLoaded', function () {
            const movingObject = document.getElementById('movingObject')

            document.addEventListener('mousemove', function (event) {
                const mouseX = event.clientX
                const mouseY = event.clientY

                // Calculate the distance from the center of the screen to the mouse pointer
                const centerX = window.innerWidth / 2
                const centerY = window.innerHeight / 2

                const deltaX = centerX - mouseX
                const deltaY = centerY - mouseY

                // Move the object in the reverse direction relative to the center
                movingObject.style.transform = `translate(${deltaX}px, ${deltaY}px)`
            })
        })