Track the cursor's movement

Looking to add an animation effect to my website. I want the navbar to follow the cursor within a limited space when hovered over. Check out this example for reference: . Here's the code I have so far, but it's not quite achieving the desired result. Can anyone offer assistance?

const cursor = document.querySelector('#cursor');

        document.addEventListener("mousemove", function(e) {
        cursor.setAttribute("style", "top: " + (e.clientY - 10) + "px; left: " + (e.clientX - 10) + "px;")
        })
        document.getElementById("navbarimg").addEventListener("mouseover",function(e) {
        cursor.classList.toggle("hover")
        })
        document.getElementById("navbarimg").addEventListener("mouseout",function(e) {
        cursor.classList.toggle("hover")
        })
document.querySelector('body').addEventListener('mousemove',follow);
        function follow(){
            var nav = document.querySelectorAll('.nav');
            nav.forEach(function(nav){
                let x = (nav.getBoundingClientRect().left)+(nav.clientWidth / 2);
                let y = (nav.getBoundingClientRect().top)+(nav.clientHeight / 2);
                let radian = Math.atan2(event.pageX-x,event.pageY-y);
                let rot =(radian*(180/Math.PI)*-1)+270;
                nav.style.transform="rotate("+ rot +"deg)";
            })
        }
body{margin:0;height:100vh;background:rgb(27,27,27);}
            #cursor{width:30px;height:30px;border:2px solid gray;border-radius:50%;position:fixed;transition-duration: 100ms;transition-timing-function: ease-out;}
            #navbarimg:before{position:absolute;top:50%;left:50%;transform:tranlate(-50%,-50%);}
            #cursor.hover{width: 100px;height:100px;opacity:0.1;background-color:gray;}
            #cursor.hover1{width: 300px;height:300px;}
<!DOCTYPE html>
<html lang="en">
  <head>
        <meta charset="UTF-8>
        <meta name="viewpoint" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Cursor</title>
   </head>
    <body>
        <div id="cursor"></div>
            <div class="nav">
            <a href="../"><img id="navbarimg"  src="navbar.svg" alt="navbar"></a>           </div>
     </body>
</html>

Answer №1

One way to accomplish this is by utilizing pre-made GSAP templates.

Check out the following link for assistance -

https://codepen.io/VweMWoz

const tl = gsap.timeline({paused: true});

tl.from(
    ".gsap-swipe",
    {
      y: 20,
      x: 20,
      rotate: -40,
      duration: 3,
      transformOrigin: '30% 80%',
      ease: Elastic.easeOut.config(1, 0.5),
    }, 0
  )
  .fromTo(
    ".swipe",
    {
      xPercent: -100
    },
    {
      duration: 1,
      xPercent: 100,
      ease: Sine.easeInOut,
      stagger: {
        each: 0.15
      }
    }, 0
  )
  .from(
    ".maskSwipe",
    {
      xPercent: -100,
      ease: Sine.easeInOut
    },
    0.4
  )
  .from(
    "#hello",
    {
      duration: 1.5,
      drawSVG: "0%"
    },
    1
  )
  .from(
    ".swoop",
    {
      duration: 2,
      drawSVG: "0%"
    },
    1
  )
  .from(
    ".line",
    {
      drawSVG: "0%",
      duration: 0.5,
      stagger: {
        each: 0.2
      }
    },
    1
  )
  .from(
    ".shape",
    {
      scale: 0,
      duration: 1.3,
      transformOrigin: "50% 50%",
      rotate: '+=random(-60, 60)',
      ease: Elastic.easeOut.config(1, 0.8),
      stagger: {
        each: 0.2
      }
    },
    0.2
  );

// ScrubGSAPTimeline(tl);

let hover = document.querySelector('.js-hover');

hover.addEventListener('mouseover', playTl);
hover.addEventListener('mouseout', resetTl);

function playTl(){
  tl.timeScale(1.25).restart();
}

function resetTl(){
  tl.progress(0).pause();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Sending an Ajax request using a dropdown menu

I'm having trouble retrieving a value from my database when a select option is chosen. The select options are generated dynamically from the same database. As a beginner in AJAX requests, I am struggling to figure out why I am only getting a blank re ...

Assistance Required in Turning Down Trade Requests on Steam That Involve Losing items

Currently, I have a code snippet from a Steam bot that processes incoming trade offers by accepting or declining them based on their state. However, my goal is to modify it in a way so that it automatically accepts trade offers where I receive items, but ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...

React higher order component (HOC) DOM attributes are causing the error message 'Unknown event handler property' to be triggered

I recently created a Higher Order Component (HOC) using recompose, but I'm encountering a React Warning every time the props are passed down. Warning: Unknown event handler property `onSaveChanges`. It will be ignored. All my properties with a speci ...

Is there a quicker method to update the state of an array of objects?

Here is my React state example: const [questionList, setQuestionList] = useState([ { _type: "radio", answer: "", point: "", question: "", options: ["A", "B"], ...

Discover the route followed by an object containing a specific key within an array of objects

Imagine having an array of dictionaries like the one below. How can I locate the object with id: 121 using JavaScript? I've been struggling to figure this out and would appreciate any hints or algorithms on how to achieve this. The desired result sho ...

Is there a way to define a specific browser for executing GWT tests?

In my GWT project, I am utilizing the HTML5 canvas feature. During testing, I rely on GWTTestCase to ensure application functionality. Some functions are only supported in Firefox starting from gecko 1.9. However, while testing with Firefox 3.0.1, err ...

Choose the value of the dynamically changing id with the same name using jQuery

Whenever I choose the id (they all have the same id number which is fetched dynamically), it displays the value of the first id. Here's how I'm trying to implement it, but it doesn't seem to be working: function editdr() { qty = $(thi ...

Ways to smoothly conclude a loading animation in real-time

I have a unique challenge of creating a loading animation using Adobe After Effects instead of CSS. The main goal is to develop an animation that continuously loops, but when the loading process stops, it ends with a distinct finishing touch. For instance, ...

Encountering an issue when running the 'cypress open' command in Cypress

I am working with a Testing framework using node, cypress, mocha, mochawesome, and mochawesome-merge. You can check out the project on this github repo. https://i.sstatic.net/ItFpn.png In my package.json file, I have two scripts defined: "scripts": { ...

Error message while running jQuery 3.2.1: issues with UL and LI

I have a link that displays the desired outcome Despite using jquery version 3.2.1, when I insert my code into Dreamweaver cc 2018, it fails to work. On my jsfiddle, the selection is sorted alphabetically, but on my web page it is not. var mylist = $( ...

"Put Jest to the test by running it with the Express

Currently, I am in the process of learning how to build an API with TypeScript and experimenting with testing it using the Jest framework. When utilizing a basic Express application like app = express() supertest(app) everything works smoothly. However, ...

Obtain a fresh SQL identifier post submission through Ajax

When a comment is submitted on a post using ajax, the comment.php script will display the new comment with its own auto-incremented SQL id. It will look something like this: // The $id variable contains the SQL id after data submission <div class="comm ...

What do I do when I encounter the error message "Provider not found for RadioControlRegistry" in Angular 2? Which provider should

Which provider should be included in the provider component? <div class="radio"> <input let match id="male" type="radio" name="gender" value="true" [(ngModel)]="isMatching" (click)="isMatching(match.value)" > Take a look at my console output ...

What could be causing JSON.parse to encounter errors when parsing a string array?

Within the following function, I am utilizing JSON.parse() on specific string arrays saved in window.sessionStorage. This allows me to apply methods like .map(). window.sessionStorage = { myArray1: "["805746|search|4","980093062|search|0","980113648| ...

Ways to address the warning "promise rejections are deprecated"

I am struggling to understand promises and keep encountering an error about unhandled promise rejection, even though I have a catch block for handling rejections. Can anyone help me figure out what I am doing wrong? Below is the code I am working with: v ...

Interactive web page with dynamic JQuery functionality and navigable page links

I am working on the project/index.html page <html> <head> <title>Index</title> <scripts...> </head> <body> Hello <div id="content"></div> <button id="page1" value="page1"/> <but ...

Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images. Due to the lack of support for Canvas and Image Object in web workers, I opte ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

Struggling with displaying nested JSON data in React components

I have a nested JSON structure running on my local server, and I'm using React to practice displaying this nested data. Currently, I am focusing on showing the day and the available time slots for that day. I have managed to extract the "days" (mon, t ...