14Jul/110
How to grab the mouse position in a browser with jQuery and HTML5
Depending on what your plans are it might become handy to know the mouse position.
The script below gives you the position relative to the page, relative to the browser window and relative to the DIV with the green color.
HTML (index.html)
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="javascript.js"></script>
<link href="style.css" type="text/css">
</head>
<body>
<div id="object"></div>
<div id="page" class="info">Page: <span></span></div>
<div id="client" class="info">Client: <span></span></div>
<div id="container" class="info">Container: <span></span></div>
</body>
</html>CSS (style.css)
* { margin: 0px; border: 0px; padding: 0px; } #object { width: 595px; height: 842px; margin: 10px; background: #cfc; border: 1px solid #666; float: left; } .info { padding-top: 100px; }
JavaScript (javascript.js)
$(function() { $("#object").mousemove(function(e) { var pageCoords = "( " + e.pageX + ", " + e.pageY + " )"; var clientCoords = "( " + e.clientX + ", " + e.clientY + " )"; var cLeft = e.pageX - $(this).offset().left; var cTop = e.pageX - $(this).offset().top; var containerCoords = "( " + cLeft + ", " + cTop + " )"; $("#page span").text("( e.pageX, e.pageY ) - " + pageCoords); $("#client span").text("( e.clientX, e.clientY ) - " + clientCoords); $("#container span").text("( e.clientX, e.clientY ) - " + containerCoords); }).click(function(e) { var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; var containerCoords = "( " + x + ", " + y + " )"; alert("You clicked: ( e.clientX, e.clientY ) - " + containerCoords); }); });
Related links:
http://docs.jquery.com/Tutorials:Mouse_Position




