Mouse position with jQuery


Posted on April 8, 2010 | Last updated: January 11, 2012 at 14:16 GMT

This HTML document was created to find the mouse position with jQuery library and specify actions when clicking on particular locations (click on the white or black square to receive the corresponding message). Find more information at jQuery Documentation, Tutorials: Mouse Position.

Open mouseposition.html directly or use the following code:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
$("#black").mousemove(function(e){
$('#position').html(e.pageX +', '+ e.pageY);
});
})
jQuery(document).ready(function(){
$("#black").click(function(e){
$('#position').html(e.pageX +', '+ e.pageY);
var x = e.pageX;
var y = e.pageY;
window.alert("You clicked on the black square and position " + "("+x+","+y+")");
});
})
jQuery(document).ready(function(){
$("#white").mousemove(function(e){
$('#position').html(e.pageX +', '+ e.pageY);
});
})
jQuery(document).ready(function(){
$("#white").click(function(e){
$('#position').html(e.pageX +', '+ e.pageY);
var x = e.pageX;
var y = e.pageY;
window.alert("You clicked on the white square and position " + "("+x+","+y+")");
});
})
jQuery(document).ready(function(){
$("#activearea").mousemove(function(e){
$('#position').html(e.pageX +', '+ e.pageY);
});
})
</script>
</head>
<body style="margin:0px;">
<div style="background:#6C6C6C;" id="activearea">
<div style="width: 100px; height: 100px; background:black;" id="black">
</div>
<div style="width: 100px; height: 100px; background:white;" id="white">
</div>
<h2>Position: <span id="position">0, 0</span></h2>
</div>
</body>
</html>
Home Design Programming Archives Contact About