Turn your mouse cursor into a dynamic and animated image using jQuery

I've implemented a code snippet that replaces the cursor with 2 images placed at a small distance from each other:

$(document).mousemove(function (e) {
        $("#firstImage").css({
            left: e.pageX,
            top: e.pageY
        });
        $("#secondImage").css({
            left: e.pageY + 50,
            top: e.pageY
        });
});

Now, I want to enhance this by adding animation -

making the images move together to the right and left alternately (the first image moves right, the second left, then the first left, and the second right), continuously.

setInterval(function () {
        $("#first").animate({
            left: "-=100px"
        }, 2000);
        $("#second").animate({
            left: "+=100px"
        }, 2000);
        $("#first").animate({
            left: "+=100px"
        }, 2000);
        $("#second").animate({
            left: "-=100px"
        }, 2000);
    }, 4000);

The issue arises when I assign the "left" css properties for the animation - the images no longer follow the mouse movement but instead return to their original positions at the start of the animation.

Answer №1

SOLUTION

HTML

<div id="custom-movement">
  <img id="left-img" src="http://xxx.png">
  <img id="right-img" src="http://xxx.png">
</div>

CSS

#custom-movement {
  position: absolute
}
#left-img, #right-img {
  position: relative
}

JS

$(document).mousemove(function (e){
  $("#custom-movement").css({
    left: e.pageX,
    top: e.pageY
  });
});

setInterval(function () {
  $("#left-img").animate({
    left: "-=100px"
  }, 2000);
  $("#right-img").animate({
    left: "+=100px"
  }, 2000);
}, 2000);

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

The outcome of the Ajax response is not in accordance with my expectations

Whenever the response from my PHP echo statement in an AJAX request is "loggedIn", I want to invoke the displayUsers function. However, it seems to always skip executing displayUsers() and goes straight to the else statement. Oddly enough, when I alert the ...

A guide to resolving the issue of invalid objects as a React child in Nextjs13

Seeking help on resolving an issue in Nextjs13, where I'm encountering the error "objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead" The scenario involves fetching ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

What is the best way to add an image element as a child of a list item only when its sibling checkbox is checked, upon clicking another button?

As a beginner in jQuery, I am working on developing a game where users can select and check 3 images from a list of ten. Following this selection, I aim to have the checked images added to a separate unordered list that I have already set up. <ul id="i ...

Is a preloader needed in a Vue.js app?

I'm currently exploring the world of Vue.js and could use some advice. When making a GET request using the axios package, I would like to display a preloader for the entire page until all the data has been loaded. While I know this is a common task i ...

Strange behavior has been observed when loading Jquery in Zend Framework

I've been working on creating a dynamic form for my Zend Framework application using JQuery and Ajax, but I've encountered a strange issue. It seems that JQuery is not functioning properly on my page unless I include a standard JQuery object like ...

Generate options for a dropdown menu based on the choice made in another dropdown menu utilizing ajax technology

Greetings, I am currently working on a JSP page that features a form with two drop-down lists. The first drop-down is designed to display the country names. While the second drop-down should show the states corresponding to the selected country. I have ...

When attempting to install material UI in my terminal, I encounter issues and encounter errors along the way

$ npm install @material-ui/core npm version : 6.14.4 Error: Source text contains an unrecognized token. At line:1 char:15 $ npm install <<<< @material-ui/core CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException ...

Dealing with promises in AngularJS within the ui-router configuration

Below is a snippet of my $stateProvider code: $stateProvider .state("home", { url: "/", template: "<employee-info-component user='$resolve.user'></employee-info-component>", resolve: { user: function(indiv ...

Enhancing the user experience of the dropdown component through improved

I have developed an accessibility feature for a dropdown component that dynamically populates values in the options menu only when the dropdown is opened. This means that it compiles the template on the fly and attaches it to the dropdown box. Dropdown HT ...

Click to stay in the background

I am currently facing an issue where opening a new tab on click redirects the focus to the child window instead of staying in the current window. I would like the popup to open without blocking and allowing me to maintain focus on my current window. The c ...

What is the best way to connect individual buttons to a dynamic div that displays different content depending on the button clicked?

Hey there! I'm diving into the world of JavaScript and HTML, and I need some guidance on creating a menu that can toggle visibility of specific content in div(s) depending on which button (picture1-12) is clicked. My idea is to have one div that can d ...

React doesn't properly display JSON data

I am facing an issue with the code below that is supposed to display data from a JSON file. Instead of showing the desired data, it only displays the h1 with curly braces. Here is the faulty code: import prod from "../../data/produtos.json"; exp ...

Shifting hues of dots within a grid according to the passing of time

As a newcomer to the world of coding, I have conceptualized an idea for a visually appealing clock. My goal is to visually represent the passage of time throughout the day. To achieve this, I have devised a grid system where each dot on the grid represents ...

A guide to creating smiley emojis using solely HTML and CSS

Is there anyone who can assist me in constructing this happy face? https://i.sstatic.net/yyYYQ.png ...

Looking for browser prefixes for the `text-align` property? We've got you covered! Use `-webkit-right` for Google Chrome and Safari, `-moz-right` for Firefox, and `-o-right` for Opera. But what about

When it comes to browser prefixes or hacks, we often think of: (for Google and Safari) text-align: -webkit-right; (for Firefox) text-align: -moz-right; (for Opera) text-align: -o-right; But what about Internet Explorer? I'v ...

What is the method to prevent scrolling on the body while allowing scrolling on a specific div element?

<html> <body> <div class="container"> <div class="menu"></div> <div class="list"></div> </div> </body> </html> .menu{ float:left; width:50%; } .list{ float:right; width:50% ...

What could be causing this code to malfunction on jsfiddle?

Why doesn't this code from W3schools work on jsfiddle? I tried to implement it here: https://jsfiddle.net/u6qdfw5f/ <!DOCTYPE html> <html> <title>W3.CSS</title> <meta name="viewport" content="width=device-width, initial ...

What is the best method to trigger a reevaluation of static parameters?

Explanation behind my question Every day, I am sent two timestamps through MQTT at 01:15 - these timestamps represent the beginning and end of a daily event (in this case, when my children are at school). It may not be the most exciting information for a ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...