Created
May 18, 2017 16:55
-
-
Save lizardking8610/f3086a7fc7293a28ba598cf9d2aef286 to your computer and use it in GitHub Desktop.
jQuery: determine distance of mouse from element
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function() { | |
| var mX, mY, distance, | |
| $distance = $('#distance span'), | |
| $element = $('#element'); | |
| 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); | |
| $distance.text(distance); | |
| }); | |
| })(); |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
"calculate the distance between the mouse cursor and the center of an element. This can be useful for triggering a function when the mouse is within a certain distance of an element. Or, you can base the value of a property, such as the width, height, or opacity of the element, on the proximity of the mouse cursor." https://css-tricks.com