Central alignment of div with cursor

I'm experimenting with creating a unique custom cursor using a <div> that trails the movement of the mouse pointer.

While the current setup works smoothly, I've noticed that when scrolling down the page, the div lags behind until the scrolling action is completed, resulting in a choppy appearance and experience.

Is there a way to prevent this issue and ensure that the <div> accurately follows the cursor without any delays?

// variables
var $cursor = $('.custom-cursor');

// Track cursor movement
$('body').on('mousemove', function(e) {
  var parentOffset = $(this).offset();
  var relX = e.pageX - parentOffset.left;
  var relY = e.pageY - parentOffset.top;
  $cursor.css({
    left: relX,
    top: relY
  });
});
body {
  background: red;
  height: 1000vh;
  position: relative;
}

.custom-cursor {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  z-index: 9999;
  background-color: yellow;
  backface-visibility: hidden;
  pointer-events: none;
  transform: translate(-50%, -50%); // Center over cursor
  transition: width .3s ease-in-out, height .3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="custom-cursor">
  </div>
</body>

Answer №1

Take a look at this fresh piece of code. I believe it can be of assistance to you.

   

var $cursor = $('.custom-cursor');

   // Track cursor movement
   var xMousePos = 0;
   var yMousePos = 0;
   var lastScrolledLeft = 0;
   var lastScrolledTop = 0;

   $(document).mousemove(function(event) {
       captureMousePosition(event);
   })

   $(window).scroll(function(event) {
       if (lastScrolledLeft != $(document).scrollLeft()) {
           xMousePos -= lastScrolledLeft;
           lastScrolledLeft = $(document).scrollLeft();
           xMousePos += lastScrolledLeft;
       }
       if (lastScrolledTop != $(document).scrollTop()) {
           yMousePos -= lastScrolledTop;
           lastScrolledTop = $(document).scrollTop();
           yMousePos += lastScrolledTop;
       }
       $cursor.css({
           left: xMousePos,
           top: yMousePos
       });
   });

   function captureMousePosition(event) {
       xMousePos = event.pageX;
       yMousePos = event.pageY;
       $cursor.css({
           left: xMousePos,
           top: yMousePos
       });
   }
body {
  background: red;
  height: 1000vh;
  position: relative;
}

.custom-cursor {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  z-index: 9999;
  background-color: yellow;
  backface-visibility: hidden;
  pointer-events: none;
  transform: translate(-50%, -50%); // Center over cursor
  transition: width .3s ease-in-out, height .3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="custom-cursor">
  </div>
</body>

Answer №2

Copy and paste the following code snippet into your project:

$( window ).scroll(function() {
  //Your code for mouse movement goes here
});

To track the current position of the mouse while scrolling, refer to this article: Get mouse position on scroll.

You can view the implementation of the code in this JS Fiddle link: http://jsfiddle.net/1byfq24g/

// Variables
var xMousePos = 0;
var yMousePos = 0;
var lastScrolledLeft = 0;
var lastScrolledTop = 0;
var $cursor = $('.custom-cursor');

// Track cursor movement
$('body').on('mousemove', function(e) {
  var parentOffset = $(this).offset();
  var relX = e.pageX - parentOffset.left;
  var relY = e.pageY - parentOffset.top;
  xMousePos = relX;
  yMousePos = relY;

  $cursor.css({
    left: relX,
    top: relY
  });
});
$(window).scroll(function(event) {
  if (lastScrolledLeft != $(document).scrollLeft()) {
    xMousePos -= lastScrolledLeft;
    lastScrolledLeft = $(document).scrollLeft();
    xMousePos += lastScrolledLeft;
  }
  if (lastScrolledTop != $(document).scrollTop()) {
    yMousePos -= lastScrolledTop;
    lastScrolledTop = $(document).scrollTop();
    yMousePos += lastScrolledTop;
  }
  console.log("x = " + xMousePos + " y = " + yMousePos);
  $cursor.css({
    left: xMousePos,
    top: yMousePos
  });
});
body {
  background: red;
  height: 1000vh;
  position: relative;
}

.custom-cursor {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  z-index: 9999;
  background-color: yellow;
  backface-visibility: hidden;
  pointer-events: none;
  transform: translate(-50%, -50%); // Center over cursor
  transition: width .3s ease-in-out, height .3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js">
</script>

<body>
  <div class="custom-cursor">
  </div>
</body>

Answer №3

Although this answer may seem late, I have been facing a similar issue and found a straightforward solution that worked for me. By setting the cursor's CSS property to position:fixed;, all the scroll animation issues were resolved completely. This fix seems to function because when set to fixed, the cursor remains relative to the viewport rather than the document itself.

// variables
var $cursor = $('.custom-cursor');

// Track cursor movement
$('body').on('mousemove', function(e) {
  var relX = e.clientX;
  var relY = e.clientY;
  $cursor.css({
    left: relX,
    top: relY
  });
});
body {
  background: red;
  height: 1000vh;
  position: relative;
}

.custom-cursor {
  position: fixed;
  width: 30px;
  height: 30px;
  border-radius: 100%;
  z-index: 9999;
  background-color: yellow;
  backface-visibility: hidden;
  pointer-events: none;
  transform: translate(-50%, -50%); // Center over cursor
  transition: width .3s ease-in-out, height .3s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div class="custom-cursor">
  </div>
</body>

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

Tips for effectively running multiple XMLHttpRequests in a loop

While running XMLHttpRequest inside .map(), everything operates smoothly. list.map(function(file) { const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () {} xhr.onerror = function () {} xhr.upload.addEventListener(& ...

First-character styling not applying to ID in CSS

My CSS :first-letter selector is effective on all p elements, however when applied to a span with the id #fletter, it doesn't seem to work... #fletter span:first-letter { font-weight: 600; font-size: 25px; } <span id="fletter"> The : ...

Discover how to achieve the detail page view in Vue Js by clicking on an input field

I'm a beginner with Vuejs and I'm trying to display the detail page view when I click on an input field. <div class="form-group row"> <label for="name" class="col-sm-2 col-form-label">Name</label> ...

State is causing a conflict by allowing multiple menus to open when mapping over Menu objects

I am currently encountering an issue with my Material UI <Menu>. The problem arises when I attempt to display some data and interface functionality by mapping over a <Card>, along with adding an <IconButton> on each card that opens a menu ...

I am interested in excluding the seconds and milliseconds from my date and time

I currently display my time in the following format: 5:34 PM I only want to show the hour and minute. How can I achieve this? ...

What is the best way to verify if a class attribute includes a specific class or not?

Below is the code snippet provided. The code fetches all classes and then checks for the presence of the 'mat-checked' class. pmanage.no_additional_cost().last().invoke('prop', 'class').then((Class) => { let ...

The static menu is malfunctioning and is disrupting the smooth operation of the website

I've created a custom Wordpress menu that should switch to a different layout when scrolling down. While the functionality works fine, I'm facing an issue where a portion of the page is lost every time the menu transitions from "relative" to fixe ...

Server becoming unresponsive following the cancellation of an AJAX call

In a specific scenario, my Ajax request to the server might take longer than usual (around 30-40 seconds). I am utilizing jQuery.ajax and specifying a timeout of 60 seconds. Consequently, if no response is received within this timeframe, the call gets canc ...

Setting a consistent theme or style for all HTML/React tags using a selector inside a specific component

Here's a simplified example of what I'm trying to do: I'm using Material UI Styles for styling my components. I want to style all the <Link> tags in my component. For instance: const useStyles = makeStyles(theme => ({ menuLink: ...

The alignment of flexbox within a list item is not positioned at the top as expected

When I place a flexbox inside a list item, the content is being pushed down by what seems to be a full line height. I have tried various CSS properties like setting margin-top: 0 for the flexbox, margin-top: 0 for its children, adding flex-wrap to the fle ...

Grails Spring Security does not maintain user login status following an ajax call

In my create view, a login form is displayed at the start if the user is not logged in. When the user attempts to log in, an ajax call is made to spring to authenticate the user, which works successfully as the logic inside the success function executes. T ...

'Without the need to refresh the page, assign a JavaScript variable from JSP on the server side.'

I'm looking for a way to assign a JavaScript variable from JSP without triggering a full page reload. While my current code successfully sets the variable, it also causes the entire page to refresh as a side effect. Here's an example in the exam ...

Having trouble with Python Selenium CSS Selector? If your element is not visible, it

My goal is to search for all hyperlinks on a webpage that contain an XML download link and download them in a continuous loop. When I click on these hyperlinks, a form pops up that needs to be completed before I can proceed with the download. However, I ...

How to position a <div> in the center of a popup <div>

I've encountered a problem trying to center a <div> within another <div> that pops up when a button is clicked. It's not my code, but it's similar. Here is the HTML: <div class="popup"> <div class="options"> ...

What is the best way to show input choices once an option has been chosen from the 'select class' dropdown menu?

When it comes to displaying different options based on user selection, the following HTML code is what I've been using: <select class="form-control input-lg" style="text-align:center"> <option value="type">-- Select a Type --</opti ...

Tips for dynamically changing the number of visible ListItems in React using a single method

I recently stumbled upon the perfect solution at this link using material-ui. The chapter on "Nested list items" caught my attention, as it only has one nested item with a method for expanding more or less. In my sidebar, I have two nested items that both ...

What is the best way to record data while initiating a process in node.js?

In my latest project, I have implemented a function that spawns a process and requires logging specific information to the console. Here is an example of how this function is structured: function processData(number) { var fileName = settings.file || "de ...

Styling HTML Text Using Your Own Unique CSS Class Style

After developing some CSS classes to define specific hex colors for my web application, I ran into issues applying these styles to text in the HTML. Despite my best efforts, I am struggling to make the styles show up as intended. CSS .custom-orange-color ...

Tips for repositioning a node element as the first child within its parent element

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'> <div>B</div> <div>C</div> <div onload='this.parentNode.prependChild();'>A&l ...

What is the process for changing one tag into a different tag?

Can someone help me with this issue? I need to change the tags in a given string from <h2> to <h3>. For example, turning <h2>Test</h2><p>test</p> into <h3>Test</h3><p>test</p>. Any suggestions o ...