Guide to aligning the center of a div with the mouse cursor using JavaScript during mouse movement

I've been trying to center a div element with the mouse cursor, following its movement. However, the current code I have offsets the positioned div from the cursor instead of aligning it perfectly.

PROCESS

The concept behind my code is to display and track the .pointer element within the .post-entry div when the mouse enters, moving along with the cursor, and hiding when the cursor leaves the div.

SOURCE CODE

HTML post item:

<article class="col-md-4 col-sm-6 post-entry">
    <a href="#" title="">
        <figure class="post-thumb">
            <img src="http://placehold.it/300x300" alt="">
            <div class="pointer" style="background: red;"></div>
        </figure><!-- End figure.post-thumb -->
    </a>
</article><!-- End article.col-md-4 post-entry -->

JavaScript:

$('.entry .post-entry').each(function() {
  $(this).on("mouseenter", mouseEnter);
  $(this).on("mousemove", mouseMove);
  $(this).on("mouseleave", mouseLeave);
});


function mouseEnter(event) {

  console.log('enter');

  var target = $(this);
  var dot = target.find('.pointer');

  var mX = (event.clientX);
  var mY = (event.clientY);

  set(
    dot, {
      x: mX,
      y: mY,
      force3D: !0
    }
  );

};

// Remaining JavaScript functions

ISSUE / PREVIEW

Although the span follows the mouse cursor, it does not align at the center but rather appears offset. View live demo here

I attempted adjusting the mX and mY variables in different ways, but without success. Likewise, @hiEven's suggested solution did not resolve the issue either.

The challenge lies in properly dividing the position for the .pointer by half, which I am struggling to implement effectively.

UPDATE

I've created two new Codepen projects showcasing the issue:

Without images: http://codepen.io/anon/pen/GqGOLv. The brown pointer correctly tracks the cursor over the first item but behaves strangely with the red pointer on the second item.

With images: http://codepen.io/anon/pen/QExOkx. Similar issues persist, especially when hovering over specific areas of the items.

The objective is to ensure that both pointers accurately follow the mouse cursor, particularly when an image is involved.

In addition, adding a margin-left disrupts the alignment of the pointer with the cursor, highlighting the complexity of achieving perfect positioning.

I'm puzzled as to why it works flawlessly in certain instances but encounters glitches with other scenarios.

Answer №1

Give this code a try

<html>
  <head>
    <style>
          #mouse_div{
            position: absolute;
            background-color: black;
          }
    </style>
    <script>
          var div_width = 100;
          var div_height = 100;
          var div_x, div_y;
          function mouse_position(event){
            var mouse_x = event.clientX;
            var mouse_y = event.clientY;
            document.getElementById("mouse_div").style.width = div_width + "px";
            document.getElementById("mouse_div").style.height = div_height + "px";
            div_x = mouse_x - (div_width / 2);
            div_y = mouse_y - (div_height / 2);
            document.getElementById("mouse_div").style.left = div_x + "px";
            document.getElementById("mouse_div").style.top = div_y + "px";
          }
    </script>
  </head>
  <body onmousemove="mouse_position(event)" onload="mouse_position(event)">
    <div id="mouse_div"></div>
  </body>
</html>

This script tracks your mouse's coordinates and adjusts the size and position of a specified div. It calculates the x-coordinate by subtracting half of the div's width from the mouse's x value to center it horizontally. The same calculation is done for the y-coordinate. Finally, the script uses JavaScript to set the CSS properties of the div element to position it correctly based on the mouse movements.

Important: Ensure that the div element's position is set to absolute for the script to work correctly.

Answer №2

Do you want the circle to follow your mouse cursor?

Try this:

transform: `translate(calc(${mx}px - 50%), calc(${my}px - 50%))

Check out the demo here

Answer №3

After reviewing my latest update, I realized that I had not followed the correct formula required to center the element .pointer to the mouse.

To achieve this effect in the mouseMove function, the calculation should be as follows:

var height = dot.height();
var width = dot.width();

var offset = target.offset();
var w = target.width();
var h = target.height();
var top = offset.top;
var left = offset.left;

var mX = (event.clientX - left) - width / 2 - 15; // 15 = padding
var mY = (event.clientY - top) - height / 2;

This formula ensures that the DOM element .pointer will accurately track the movement of the user's mouse. Although I do not fully understand why it works, subtracting the offset from the previous item from the current clientX coordinates resets the position of the second item to zero, effectively causing the pointer to align with the left side of each item.

You can view a demonstration of the code in action here: http://codepen.io/anon/pen/AXdxZO?editors=0110

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

Setting a fixed data value within a div for subsequent retrieval through a function

I found a helpful example that demonstrates how to convert numbers into words. You can check it out here. The function for converting numbers into words is implemented in the following HTML code: <input type="text" name="number" placeholder="Number OR ...

Tips on implementing a circular progress bar with locomotive scroll functionality

Can anyone help me integrate progress functionality with Locomotive Scroll using JavaScript? Link to CodePen for reference Check out this code snippet from Locomotive Scroll that calculates the percentage of pages scrolled: const scroller = new Locomotiv ...

Email address string loses the '+"' when using AJAX

My ajax code has been working well in most cases, but when I tried using it for updating user details on my page, I noticed that the ""+"" symbol was getting lost if used in an email address (such as <a href="/cdn-cgi/l/email-protection" class ...

Avoid having logs displayed on the server end when utilizing console.log commands

Being new to JavaScript and Node.js, I am attempting to have my application output logs on the server side. getUser.onclick = function () { console.log('Server running at http://127.0.0.1:1337/'); var req = new XMLHttpRequest(); r ...

Integrate the dForm plugin with a convenient time picker widget

Currently, I am attempting to integrate a time picker widget into a jQuery plugin called dForm. The specific timepicker widget can be found at the following link: https://github.com/jonthornton/jquery-timepicker Despite reviewing the dForm documentation, ...

Error: JSON parsing failed due to an unexpected character, resulting in null data

Many people have asked similar questions on the same topic, but I have not been able to find a solution for my specific problem. Below is the code snippet that I am working with: $.post("show_search_results.php", {location_name: ""+location_name+"", key: ...

How can you notice when a DOM element is deleted from the page?

I am in the process of creating a custom directive that will ensure only one element is active at a time. Directive: displayOneAtATime Description: This directive can be applied to a DOM node to guarantee that only one element with this directive can be v ...

Surprising outcomes when using Mongoose

Questioning Unusual Behavior There is a model in question: //test.js var mongoose = require('../utils/mongoose'); var schema1 = new mongoose.Schema({ name: String }) var schema2 = new mongoose.Schema({ objectsArray: [schema1] }); schema1.pre( ...

Issue encountered: Cannot locate module: Error message - Unable to find 'stream' in 'C:devjszip-test ode_modulesjsziplib' folder

I am encountering an issue in my angular 7 application while using jszip v3.2.1. During the project build process (e.g., running npm start), I receive the following error message: ERROR in ./node_modules/jszip/lib/readable-stream-browser.js Module not fo ...

Using Express JS to implement a post method for multipart form data transmission

I recently attempted to send form data to my express js server. Below is the code snippet from my pug file: form(action="/profile" method="post" enctype="multipart/form-data") input(type="file" accept="image/*" name="profileimage") input(type="text" nam ...

Building a Meteor query in MongoDB using $in operator while handling duplicate values

I have a collection of songs that I want to present to a user. Each song is associated with a specific id. The issue I am encountering is that some songs should be displayed multiple times. Currently, I am using the $in operator in my MongoDB query, but it ...

Cease processing ajax requests on the server side

After conducting thorough research on the topic of canceling ajax requests, I have come across several threads discussing this matter. One particular thread caught my attention: Abort Ajax requests using jQuery The post explains how when you use the abor ...

What is the best way to retrieve a linked filter in Vue from another?

I have created a file to store filters linked to my Vue object, and it is being imported into my App.js. One of the filters I have needs to use another filter: Vue.filter('formatDateTime', value => { if (value) return moment(String(value ...

Emit Observables within deeply nested callback functions

Hey there! I'm currently working on a web app using Angular2/4 and I've encountered an issue with Observables. My goal is to call a function within a component and then have some code executed once that function completes. Here's the releva ...

The battle between dynamic PDF and HTML to PDF formats has been a hot

In my current project, I am developing multiple healthcare industry dashboards that require the functionality to generate PDF documents directly from the screen. These dashboards do not involve typical CRUD operations, but instead feature a variety of char ...

Obtaining the client's IP address using socket.io 2.0.3: a comprehensive guide

Currently, I am facing a challenge using socket.io v2.0.3 in my node.js server as I am unable to retrieve the client's IP address. Although there are several suggestions and techniques on platforms like stackoverflow, most of them are outdated and no ...

Discovering the true width of elements that have overflow hidden in IE7 using jQuery

I am dealing with a dynamic list that contains around 50 elements, but the exact number may vary. <div style="width:465px;"> <ul> <li>aaa</li> <li>aaa</li> <li>aaa</li> <li>aaa& ...

Obtain the value of a URL parameter on a webpage without needing to refresh the

I have a list of records on a webpage, each with a unique URL pointing to another page with a parameter in the URL. When any of these records are clicked, I want to display the value of the URL parameter in an alert without reloading the page. <script& ...

The function DataTable is not defined in jQuery(...)

When attempting to use jQuery DataTable with Angular JS in my ServiceNow application, I encountered the error message jQuery(...).DataTable is not a function. To resolve this issue, I created a variable 'j' to prevent conflicts between jQuery and ...

Display a division upon choosing an option

I am working on a project that involves a selection menu in the form of a drop-down list. <select> <option id="one" value="something">Car</option> <option id="two" value="anything">Plane</option> </select> Also, I ...