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.