15 April, 2013

How to Get Mouse Cursor Position in jQuery

Introduction

In this 
jQuery snippet I will explain how to get current mouse or cursor position in jQuery.

Description: 
   
In previous posts I explained jQuery Allow only numbers in textbox, jQuery Accordion Menu Example,
jQuery lightbox slideshow, jQuery Create Rounded Corners Textbox and many articles relating to JQuery,Asp.net. Now I will explain how to get current position of mouse or cursor in JQuery.

To implement this functionality we need to write the code like as show below


<script type="text/javascript">
$(function() {
$(document).mousemove(function(e) {
$('#lbltxt').html("X Axis: "+e.pageX+"<br/>"+ "Y Axis: "+e.pageY);
})
})
</script>

If you want to see it in complete example write the following code in your aspx page


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>jQuery Get Mouse or Cursor Position</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(function() {
$(document).mousemove(function(e) {
$('#lbltxt').html("X Axis: "+e.pageX+"<br/>"+ "Y Axis: "+e.pageY);
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<label id="lbltxt" />
</div>
</form>
</body>
</html>
Live Demo

To check Live demo try to move your cursor and check x and y axis values below

No comments:

Post a Comment