Are you searching for how to detect current mouse coordinates using jQuery? You can use the jQuery event.pageX and event.pageY in combination with the jQuery offset() method to get the position of mouse pointer relative to an element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>How to detect current mouse coordinates using jQuery</title> <style> #box{ width:400px; height:300px; background: #f2f2f2; border: 1px solid #000; } </style> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script> $(document).ready(function() { $("#box").mousemove(function(event){ var relX = event.pageX - $(this).offset().left; var relY = event.pageY - $(this).offset().top; var relBoxCoords = "(" + relX + "," + relY + ")"; $(".mouse-cords").text(relBoxCoords); }); }); </script> </head> <body> <div id="box"></div> <p>Coordinates of mouse pointer with respect to the DIV box are: <strong class="mouse-cords"></strong></p> </body> </html> |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.