I just want to preface this post with the disclaimer that I am a beginner with javascript/jquery and would really appreciate it if explanations/examples came slow :)
Editing the post to narrow the question for clarity: I want a HTML element to follow your cursor only if the cursor is hovering it; once the cursor "leaves" the element, I want the element to discontinue its following.
So far I have found code (from both w3schools: https://www.w3schools.com/jquery/event_hover.asp and another post on StackOverflow: how to animate following the mouse in jquery) to implement the "follow cursor" feature and to make it so that this occurs only once the cursor hovers an element: https://jsfiddle.net/rtwrtw8/og7ej0n8/
$(document).ready(function(){
$("#follower").hover(function(){
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(e){
mouseX = e.pageX;
mouseY = e.pageY;
});
// cache the selector
var follower = $("#follower");
var xp = 0, yp = 0;
var loop = setInterval(function(){
// change 12 to alter damping higher is slower
xp += (mouseX - xp) / 12;
yp += (mouseY - yp) / 12;
follower.css({left:xp, top:yp});
}, 30);
}, function(){
$(this).css("background-color", "pink");
});
});
#follower{
position : absolute;
background-color : red;
color : white;
padding : 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follower">Starts following once hovers</div>
The issue, however, is that the box continues to follow the cursor even if the cursor is no longer hovering over the element (which is confirmed by the box turning pink, as specified in the code). Instead, the box should just stay in the position when the cursor was last hovering over it.
If anyone has any suggestions as to how to implement this feature or knows of any working examples, I would greatly appreciate it! Thanks in advance!