Any tips for modifying my jQuery script so that a div smoothly tracks my cursor's movement?

My jQuery code creates a span in the shape of a circle following my cursor, but I saw another website that uses transform: translate() instead of top and left properties for smoother cursor movement. Can someone help me modify the code to use transform: translate()?

JSFiddle: https://jsfiddle.net/oj70y5Lm/

CSS, JQuery and HTML

jQuery(document).ready(function() {

  var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;

  $(document).mousemove(function(e){
    mouseX = e.pageX - 20;
    mouseY = e.pageY - 20; 
  });

  setInterval(function(){
    xp += ((mouseX - xp)/3);
    yp += ((mouseY - yp)/3);
    $("#circle").css({ transform: 'translate(' + xp +'px, ' + yp + 'px)' });
  }, 20);

});
body, html {
  position: relative;
  height: 100%; 
  width : 100%;  
  margin: 0;
}

.circle {
    position: absolute;
    background: #000000;
    opacity: .075;
  width: 40px; 
  height: 40px; 
    border-radius: 50%;  
    pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="circle" class="circle"></span>

Answer №1

Opt for CSS transitions over using JS with a 20ms interval. CSS always provides a smoother animation compared to timed JS

jQuery(document).ready(function() {

  var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;

  $(document).mousemove(function(e){
    mouseX = e.pageX - 20;
    mouseY = e.pageY - 20;
    
    xp += ((mouseX - xp)/3);
    yp += ((mouseY - yp)/3);
    $("#circle").css({left: xp +'px', top: yp +'px'});
  });
});
body, html {
  position: relative;
  height: 100%; 
  width : 100%;  
  margin: 0;
}

.circle {
    position: absolute;
    background: #000000;
    opacity: .075;
  width: 40px; 
  height: 40px; 
    border-radius: 50%;  
    pointer-events: none;
    transition: left 20ms ease-in-out, top 20ms ease-in-out;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="circle" class="circle"></span>

Answer №2

I've figured out the solution!

Here is the updated code snippet:

$("#circle").css('transform', 'translate(' + xp + 'px, ' + yp + 'px)');

JSFiddle: https://jsfiddle.net/oj70y5Lm/1/

CSS, JQuery and HTML

<span id="circle" class="circle"></span>


body, html {
    position: relative;
    height: 100%; 
    width : 100%;  
    margin: 0;
}

.circle {
    position: absolute;
    background: #000000;
    opacity: .075;
    width: 40px; 
    height: 40px; 
    border-radius: 50%;  
    pointer-events: none;
}

jQuery(document).ready(function() {

  var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;

  $(document).mousemove(function(e){
    mouseX = e.pageX - 20;
    mouseY = e.pageY - 20; 
  });

  setInterval(function(){
    xp += ((mouseX - xp)/3);
    yp += ((mouseY - yp)/3);
    $("#circle").css('transform', 'translate(' + xp + 'px, ' + yp + 'px)');
  }, 20);

});

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 manipulation of the DOM is not possible within the AJAX success function

I'm curious about the issue I am facing with changing the 'this' element on AJAX success. Despite my efforts to switch classes and add a new data attribute to the anchor tag in ajax success, it doesn't seem to be working. Interestingly, ...

The element is not occupying the full width within the div container

I'm working with a div that contains some elements. My goal is to have these elements span the entire width of the container div. .container { height: 100px; width: 100px; display: flex; flex-direction: column; overflow: scroll; borde ...

How may I utilize CSS to generate a dynamically resizing rotated triangle that adjusts based on the text content?

Looking to add a dynamic badge in the top left corner of a div that adjusts its size based on the text content. Check out this example: http://jsfiddle.net/sbick/npxaasht/ <article> <div class="triangle"> <span>NEW</span ...

Is there a way to adjust my input value to correspond to December of 2022?

I am working on a project where I need to set a default month and year that the user cannot modify. They should only be able to change the date in December months. Any tips on how I can achieve this? <input id="input_date" type="date&qu ...

Utilize Ajax and Nodejs to inject dynamic content into your webpage

Seeking assistance in implementing a project where a navigation bar on the page contains various items, and I aim to display the content of each tab without reloading the entire page. Utilizing Nodejs with the ejs template engine, my research hasn't l ...

tips on customizing buttons within form groups

I have set up two separate form-groups: My goal is to click on each button within each group and toggle its style from grey to green, and vice versa. However, when I click on a button, all buttons within the group turn grey except for the one that was cli ...

What is the best way to extract the lodash score from a URL using JSON parsing?

Can someone help me figure out how to extract and store the names from a URL into an array, then parse JSON data to retrieve the lodash score and convert it into a whole number? Any assistance would be greatly appreciated. <head> <title> ...

NodeJS package 'jquery' npm not functioning properly (issue with $.on())

I've successfully installed and loaded jquery by using $ = require('jquery'); However, when I attempt to utilize it: app.get('/', function (req, res) { res.render('index'); $.on('ready', function () { ...

Enable automatic scrolling when a button on the previous page has been clicked

Imagine there are two buttons (Button 1 and Button 2) on a webpage (Page A). Clicking on either button will take you to the same external page (Page B). How can we ensure that Button 1 takes you to the top of Page B, while Button 2 automatically scrolls do ...

Which is better for posting data via ajax: using JSON.stringify() or default URL encoding?

Is there a specific advantage to using JSON.stringify() when posting a complex object compared to allowing default url encoding with jQuery.ajax? The MVC WebApi I am utilizing is able to handle both types of requests without any issues, so the need to send ...

Using jQuery, what is the best way to invoke a method within code-behind in asp.net with c#?

My website's structure is based on master and content pages, with Multiviews in the content pages that contain RadComboBoxes. Among the RadComboBoxes, two act as parent and child dropdowns, such as country and city selection. To dynamically populate ...

When using @font-face, Chrome supports it while IE and Firefox do not

I am finding this quite perplexing. I am currently using font-squirrel to download a web kit in order to display a custom font. You can access the font through this link: If you visit the homepage now: The main text in the center reads "Custom Built Webs ...

Troubleshooting AJAX hover functionality issue

Here is the content that loads through AJAX: <div class="grid"> <div class="thumb"> <img alt="AlbumIcon" src="some-image.jpg"> <div style="bottom:-75px;" class="meta"> <p class="title">Title< ...

Issues with the performance of the Responsive Image Slider

Having trouble with the carousel on my website. The Navigation Bar is working, but the image slider isn't showing up despite trying multiple approaches. Bootstrap is properly linked and I've read through the documentation for the Bootstrap Carous ...

`Javascript framework suggests ajax navigation as the preferred method`

What is the best way to handle ajax navigation using jQuery? I have recently experimented with a simple jQuery ajax code to implement ajax-based navigation for all the links on a webpage. $('a').click(function(e){ e.preventDefault(); ...

Can HTML/CSS be used to specifically target handheld mobile devices?

I am looking to optimize my video display in HTML by only showing it on desktop browsers. The difference in bandwidth between desktop and mobile devices is affecting the performance of mobile browsers, so I want to target only desktop users. Is there a way ...

Utilizing DataTables to dynamically populate a table with data fetched from an AJAX request

I'm currently in the process of developing a program that showcases various topics within a specific subject. My main query revolves around whether or not the DataTable functionality will be compatible with this particular setup. The following is th ...

What is the best method for styling arrays displayed by React in version 15 using CSS?

React v15 has made a change where elements of arrays in JSX are now rendered as <!--react-text:some_id-->text<!--/react-text--> instead of spans. I've searched for a solution but haven't been able to figure out how to apply CSS styles ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...