www.webdeveloper.com
Results 1 to 2 of 2

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

  1. #1
    Join Date
    Jul 2010
    Posts
    135

    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.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,441

    Lightbulb

    No need to use JQuery, but you can modify it if desired.
    Code:
    <!DOCTYPE HTML>
    <html>
    <head>
    <title> Untitled </title>
    <meta charset="utf-8">
    <style type="text/css">
    #divID{
      top:50px;
      left:150px;
      position:fixed;
    }
    </style>
    
    </head>
    <body>
    <form id="myForm">
    <input type="text" id="coordinates" value=""><br>
    <div id="divID">
    <img id="pic" src="http://www.nova.edu/hpd/otm/pics/4fun/PANIC.JPG">
    </div>
    </form>
    
    <script type="text/javascript">
    // 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;
    
        window.onmousemove = handleMouseMove;
        setInterval(getMousePosition, 100); // setInterval repeats every X ms
    
        function handleMouseMove(event) {
            event = event || window.event; // IE-ism
            mousePos = {
                x: event.clientX,
                y: event.clientY
            };
        }
    
        function getMousePosition() {
            var pos = mousePos;
            if (!pos) {
                // We haven't seen any movement yet
            }
            else { document.getElementById('coordinates').value = pos.x +' : '+ pos.y;
                // Use pos.x and pox.y
            }
        }
    })();
    </script>
    
    </body>
    </html>

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles