Home > database >  How to make a div move with the mouse cursor smoothly?
How to make a div move with the mouse cursor smoothly?

Time:11-18

I am trying to achieve the mouse effect on carousel (https://advertising.nytimes.com/custom-content/). the cursor should change when I hover over the container. I got it working but it is stutters a lot. How to make it smooth? the stutter occurs when I add the conditional statement. Please help.

<style>
            .img {
                width: 100px;
                height: 100px;
                object-fit: cover;
                position: fixed;
                top: 0;
                left: 0;
            }
            .container {
                width: 700px;
                height: 900px;
                background-color: orangered;
                overflow: hidden;
                cursor: none;
            }
</style>


<div >
            <img
                
                src="https://images.unsplash.com/photo-1472457897821-70d3819a0e24?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2669&q=80"
            />
 </div>
        <script>
            const container = document.querySelector(".container");
            const img = container.querySelector(".img");

            document.addEventListener("mousemove", (e) => {
                if (event.target == container) {
                    img.style.transform = `translate3d(${e.clientX}px, ${e.clientY}px, 0)`;
                }
            });
        </script>

CodePudding user response:

It is as simple as adding a Logical OR next to the event.target == container. It was moving weirdly because when your mouse would go over the image it would not be the target anymore.

To fix this we need to add an ID to the image so we can source it in our event.target. So out <img> would look something like this

<img id"img" src="https://images.unsplash.com/photo-147245789782170d3819a0e24ixlib=rb4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=2669&q=80"/>

After we set the id we are able to add the logical OR statement, it would look like this

event.target == container || picture

Hope I could help!

  • Related