Reputation: 33691
I would like to have a function run when the mouse is X distance away from an element.
I assume mousemove event should be moved, but since the element may not always be in the same place I'm not sure how to get the mouse position relative to the element?
Does anyone have an example of something similar?
Upvotes: 2
Views: 608
Reputation: 44740
var mX, mY, distance;
$element = $('#YourElementID');
function calculateDistance(elem, mouseX, mouseY) {
return Math.floor(Math.sqrt(Math.pow(mouseX - (elem.offset().left+(elem.width()/2)), 2) + Math.pow(mouseY - (elem.offset().top+(elem.height()/2)), 2)));
}
$(document).mousemove(function(e) {
mX = e.pageX;
mY = e.pageY;
distance = calculateDistance($element, mX, mY);
// do your stuff with distance
});
Upvotes: 2
Reputation: 13558
You will need to bind to the mousemove
event, store the coordinates of your elements corners in a global variable and keep checking at every pixel the mouse moved until the vector between current mouse position and your objects coordinates is of length X. that would then be the moment to trigger your custom event which you bound some function to.
i am unaware of a plugin that already does that, so make sure to post a link to the plugin you write here. :)
Upvotes: 0