/    Sign up×
Community /Pin to ProfileBookmark

How to detect mouse position over image? (maybe in JQuery)

Hello,
I have a need of function to detect mouse cursor position – how far from edge of is the mouse. Because I want to return true if the mouse is more then 40px from the edge if image. Have no idea how to do it? I am using JQuery.

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@JMRKERJun 24.2013 — No need to use JQuery, but you can modify it if desired.
<i>
</i>&lt;!DOCTYPE HTML&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt; Untitled &lt;/title&gt;
&lt;meta charset="utf-8"&gt;
&lt;style type="text/css"&gt;
#divID{
top:50px;
left:150px;
position:fixed;
}
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;
&lt;form id="myForm"&gt;
&lt;input type="text" id="coordinates" value=""&gt;&lt;br&gt;
&lt;div id="divID"&gt;
&lt;img id="pic" src="http://www.nova.edu/hpd/otm/pics/4fun/PANIC.JPG"&gt;
&lt;/div&gt;
&lt;/form&gt;

&lt;script type="text/javascript"&gt;
// For: http://www.webdeveloper.com/forum/showthread.php?279919-How-to-detect-mouse-position-over-image-%28maybe-in-JQuery%29

(function() { // Modified from: http://stackoverflow.com/questions/7790725/javascript-track-mouse-position
var mousePos;

<i> </i>window.onmousemove = handleMouseMove;
<i> </i>setInterval(getMousePosition, 100); // setInterval repeats every X ms

<i> </i>function handleMouseMove(event) {
<i> </i> event = event || window.event; // IE-ism
<i> </i> mousePos = {
<i> </i> x: event.clientX,
<i> </i> y: event.clientY
<i> </i> };
<i> </i>}

<i> </i>function getMousePosition() {
<i> </i> var pos = mousePos;
<i> </i> if (!pos) {
<i> </i> // We haven't seen any movement yet
<i> </i> }
<i> </i> else { document.getElementById('coordinates').value = pos.x +' : '+ pos.y;
<i> </i> // Use pos.x and pox.y
<i> </i> }
<i> </i>}
})();
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
×

Success!

Help @crazy_boy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...