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 interface IJobDetails cannot be assigned to type null

In the code snippet below, I have created an interface called ClientState1. Now, I am attempting to define a constant named descriptionJobDetails with the type ClientState1, specifically for IJobDetails. However, I am encountering an error as illustrated ...

Steps for positioning an image to overlap the background image

Do I need JavaScript or is HTML and CSS sufficient? If so, should I utilize position or other properties for that? If my description is unclear, a visual demonstration in the form of an image might help. ...

Find elements in a jQuery selector using two different potential values

Is there a way to filter elements with the data-value attribute set to either 1 or 2? I have tried using: $('body').find('[data-value="1|2"]'); I thought the pipe character could be used in jQuery for selecting between different value ...

Show information in tooltips across several rows

Within my Vue.js component, I am attempting to craft a custom tooltip text that consists of multiple lines. <div class="toolTip"> Shift ('+i+') </div> <div class="hide"> <div class="w-full"&g ...

A numeric input area that only accepts decimal numbers, with the ability to delete and use the back

I have successfully implemented a code for decimal numbers with only two digits after the decimal point. Now, I am looking to enhance the code in the following ways: Allow users to use backspace and delete keys. Create a dynamic code that does not rely o ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

The feature of Google street view is not supported within the tabs on WordPress

I'm experiencing some issues with displaying Google maps and street view using the Wp Google Map WordPress plugin within tabs. The map displays perfectly on the first tab where I placed the short code for the map, but on the second tab where I placed ...

Creating a Vertical Stack of Three Divs in ReactJS

Just Getting Started: As a newcomer to ReactJS and web development in general, I've put effort into researching my question without success. I acknowledge that the solution might be simpler than I think, so I apologize in advance if it turns out to b ...

Error 403 with Firefox on Font Loading for CodeIgniter Website

Utilizing font-face in CSS to integrate custom fonts onto a web application being developed with CodeIgniter. This is the CSS code: @font-face { font-family: 'UniversLT-UltraCondensed'; src: url('../Fonts/LTUnivers/universlt59ultrac ...

Generating elements with the help of node.js and express.js

Currently, I have an application that operates entirely on the client-side. When an XML file is uploaded to the app, it uses jQuery to create new elements and display them on the page. The content of these elements varies based on the uploaded file's ...

What steps can be taken to modify this jQuery code so that any changes made are also saved to localStorage

I have successfully used jQuery to change the background color of all my divs with the same class (userNumber1) when I check its checkbox. However, I am now looking for a way to save these changes to localStorage, so that they persist each time the page is ...

Adding a panel dynamically with Bootstrap incorrectly

I have been using the Collapse panel in Bootstrap and it was working perfectly when implemented statically. However, I encountered an issue when trying to add it dynamically. HTML <form> <div class="form-group" > <label for="c ...

How to locate an ID following an AJAX call in jQuery

I am experiencing an issue with a button that is supposed to print a form containing data based on different IDs, where each form has a unique ID. The problem arises when the main page fails to locate these IDs. Below is the JavaScript code responsible f ...

Can this layout be achieved using DIV elements?

Struggling to create a unique HTML/CSS layout that extends beyond the center? Imagine a standard horizontally centered page, but with one div expanding all the way to the right edge of the browser window. This design should seamlessly adjust to window res ...

When a table undergoes a dynamic reload, the formatting for the columns fails to display properly

After fetching image metadata from an API call, a table is dynamically generated on page load. Subsequently, when new images are uploaded, the function responsible for building the table is called again to include this new data. However, despite the CSS st ...

What are the best practices for avoiding text wrapping around a DIV?

I have scoured this site extensively, searching for a solution to my problem. What I thought was a simple issue has left me frustrated after hours of trying to figure it out on my own. So, I've finally admitted defeat and turned to seek help... Here& ...

Guide on how to modify the CSS styling of a particular <td> element when its parent contains a specific class

.webgrid-table td, th { border: 1px solid #98bf21; padding: 3px 7px 2px; } I am facing an issue where the style defined above is being applied to all td elements. However, I want to exclude the styling for a td that is within a tr element with the ...

The "if" statement carries out the identical action each time it is executed

Despite my efforts to toggle the value of the turn variable every time the if statement runs, I keep encountering the same outcome. It appears that turn consistently evaluates as 2. Below is the code snippet in question: $(function() { var turn = 2; ...

Is there a way to confine a jquery script within the dimensions of the container div?

I have recently created a gallery with navigation buttons in jQuery. As a newcomer to jQuery, I wrote a small script that adjusts the margin of a div container by a fixed amount. The script is functioning properly, but it extends beyond the top and bottom ...

The value of the jQuery data on click event handler becomes 'undefined' when used within an AJAX handler

When I click on the Positive or Negative buttons, a jQuery event handler function is triggered. Each button passes different data objects to the handler. However, within the AJAX POST handler, I am unable to access the data from the click event. $('# ...